JS缓冲运动
跟匀速运动不同的是,缓冲运动的运动方式是先快后慢,所以必须想办法让速度越来越慢。这里用iTarget作为参数代表目标点,可以通过(iTarget-oDiv.offsetLeft)/15(分母自取,可控制速度快慢)这样的算法让速度越来越慢,到最后除出来的是小数,所以必须要向上和向下取整以至精准。
<!doctype html> <html> <head> <meta charset="utf-8"> <title>缓冲运动</title> <style> #div1{width: 150px; height: 150px; background: blue; position: absolute;left: 0px; top:50px;} </style> <script type="text/javascript"> window.onload = function(){ var oDiv = document.getElementById('div1'); var oBtn = document.getElementById('btn'); oBtn.onclick = function(){ StartMove(300); } } var timer = null; function StartMove(iTarget) { clearInterval(timer); oDiv = document.getElementById('div1'); timer = setInterval(function(){ var speed = 0; if(oDiv.offsetLeft>iTarget) { speed = Math.floor(-(iTarget-oDiv.offsetLeft)/15); } else { speed = Math.ceil((iTarget-oDiv.offsetLeft)/15); } if(oDiv.offsetLeft>=iTarget) { clearInterval(timer); } else { oDiv.style.left = oDiv.offsetLeft + speed +'px'; document.getElementById('txt').value = oDiv.style.left; } },30) } </script> </head> <body> <input id = "txt" type = "text" value = "" /> <input id = "btn" type = "button" value = "开始运动" /> <div id = "div1"> </div> </body> </html>

浙公网安备 33010602011771号