一、js的运动
匀速运动
- 清除定时器
- 开启定时器
- 运动是否完成:a、运动完成,清除定时器;b、运动未完成继续
匀速运动停止条件:距离足够近 Math.abs(当然距离-目标距离) < 最小运动距离
div的匀速运动(简单运动)
<!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> <style> #div1{ width:100px; height:100px; background:red; position:absolute; top:50px; left:500px;} span{ width:1px; height:300px; background:black; position:absolute; left:300px; top:0; display:block;} </style> <script> window.onload = function() { var oBtn = document.getElementById('btn1'); var oDiv = document.getElementById('div1'); oBtn.onclick = function() { startMove(oDiv, 300); }; }; var timer = null; function startMove(obj, iTarget) { clearInterval(timer); timer = setInterval(function(){ var iSpeed = 0; if(obj.offsetLeft < iTarget) { iSpeed = 7; } else { iSpeed = -7; } if( Math.abs( obj.offsetLeft - iTarget ) < 7 ) { clearInterval(timer); obj.style.left = iTarget + 'px'; } else { obj.style.left = obj.offsetLeft + iSpeed + 'px'; } }, 30); } </script> </head> <body> <button id="btn1">移动</button> <div id="div1"></div> <span></span> </body> </html>