<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #div1{ width: 200px; height: 200px; background: #CCC; position: absolute; left: 0px; } #div2{ width: 1px; height: 500px; background: black; position: absolute; left: 500px; } #div3{ width: 1px; height: 500px; background: black; position: absolute; left: 900px; } </style> <script> window.onload=function () { var oDiv1=document.getElementById("div1"); var oBtn1=document.getElementById("btn1"); var oBtn2=document.getElementById("btn2"); oBtn1.onclick=function (ev) { move(500); } oBtn2.onclick=function (ev) { move(900); } } function move(target) { var oDiv1=document.getElementById("div1"); var timer=null; var speed; clearInterval(timer); timer=setInterval(function () { speed=(target-oDiv1.offsetLeft)/10; if(speed>0) { speed=Math.ceil(speed); } else { speed=Math.floor(speed); } if(Math.abs(target-oDiv1.offsetLeft)==0) { // oDiv1.style.left=target+'px'; //匀速运动的时候,如果靠不到目的地前,差点距离也行,然后使用障眼法 clearInterval(timer); } else { oDiv1.style.left=oDiv1.offsetLeft+speed+'px'; } },30); } </script> </head> <body> <input type="button" id="btn1" value="500"> <input type="button" id="btn2" value="900"> <div id="div1"></div> <div id="div2"></div> <div id="div3"></div> </body> </html>
JS缓冲运动
猜你喜欢
转载自blog.csdn.net/yangyalun/article/details/79893565
今日推荐
周排行