核心思想:
(1)相对于匀速移动,盒子每次移动的步长都是变化的,公式:盒子位置=盒子本身位置+(目标位置-盒子本身位置)/10
(2)在盒子位置与目标距离小于10px时,其步长必然是小数,又由于offsetLeft的变态的逢4进值,那么只要小数点的值小于4就会停滞不前
(3)所以要么往上取整,要么往下取整
1、Math.ceil
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div { width: 100px; height: 100px; background-color: pink; position: absolute; } </style> </head> <body> <button>点击</button> <div></div> <script> var btn = document.getElementsByTagName("button")[0]; var divEle = document.getElementsByTagName("div")[0]; var timer = null; btn.onclick = function () { clearInterval(timer); timer = setInterval(function () { //当目标距离与实际距离小于10px时,会以1px的速度前进 var step = (400 - divEle.offsetLeft) / 10; step = Math.ceil(step); divEle.style.left = divEle.offsetLeft + step + "px"; if (Math.abs(400 - divEle.offsetLeft) <= Math.abs(step)) { divEle.style.left = "400px"; clearInterval(timer); } }, 15) } </script> </body> </html>
2、Math.floor
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div { width: 100px; height: 100px; background-color: pink; position: absolute; left: 400px; } </style> </head> <body> <button>点击</button> <div></div> <script> var btn = document.getElementsByTagName("button")[0]; var divEle = document.getElementsByTagName("div")[0]; var timer = null; btn.onclick = function () { clearInterval(timer); timer = setInterval(function () { //当目标距离与实际距离小于10px时,会以1px的速度前进 var step = (0 - divEle.offsetLeft) / 10; step = Math.floor(step); divEle.style.left = divEle.offsetLeft + step + "px"; if (Math.abs(0 - divEle.offsetLeft) <= Math.abs(step)) { divEle.style.left = 0; clearInterval(timer); } }, 15) } </script> </body> </html>
3、封装
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div { width: 100px; height: 100px; background-color: pink; position: absolute; left: 0px; } </style> </head> <body> <button>回到起点</button> <button>回到200</button> <button>回到400</button> <div></div> <script> var btn1 = document.getElementsByTagName("button")[0]; var btn2 = document.getElementsByTagName("button")[1]; var btn3 = document.getElementsByTagName("button")[2]; var divEle = document.getElementsByTagName("div")[0]; btn1.onclick = function () { animate(divEle, 0); } btn2.onclick = function () { animate(divEle, 200); } btn3.onclick = function () { animate(divEle, 400); } function animate(ele, target) { clearInterval(ele.timer); ele.timer = setInterval(function () { var step = (target - ele.offsetLeft) / 10; step = step > 0 ? Math.ceil(step) : Math.floor(step); ele.style.left = ele.offsetLeft + step + "px"; if (Math.abs(target - ele.offsetLeft) <= Math.abs(step)) { ele.style.left = target + "px"; clearInterval(ele.timer); } }, 15); } </script> </body> </html>