缓速动画原理
<!DOCTYLE html> <html> <head> <meta charset="uft-8" /> <style> #box {width:100px; height: 100px; background:#dfd; position:absolute; left:100px; top:100px;} </style> </head> <body> <button id="btn">600</button> <div id="box"></div> </body> </html> <script> var btn = document.getElementById('btn'); var box = document.getElementById('box'); var target = 600; var step = 0; var timer = null; btn.onclick = function () { timer = setInterval(function () { step =(target - box.offsetLeft)/10;//要放到定时器里面 step = step > 0 ? Math.ceil(step) : Math.floor(step); box.style.left = box.offsetLeft+ step +'px'; if(box.offsetLeft>= target) { clearInterval(timer) } console.log(box.offsetLeft) },40) } </script>