-
获取要运动的box
-
清除定时器,防止连续点击按钮时,加速运动
-
获取当前box的offsetlLeft值,并确定step的步伐,由于目前是正数所以向上取整就好
-
更新当前current值(每次执行时都加上step值)
-
当目标值等于当前值时,清除定时器
* {
margin: 0;
padding: 0;
}
#box {
width: 100px;
height: 100px;
background: pink;
position: absolute;
}
<button id = "btn">运动到400</button>
<div id = "box"></div>
var btn = document.getElementById('btn');
var box = document.getElementById('box');
var timer = null;
btn.onclick = function () {
clearInterval(timer);
timer = setInterval(function () {
var current = box.offsetLeft;
var step = (400 - current) / 10;
step = Math.ceil(step);
current += step;
box.style.left = current + 'px';
if(current == 400) {
clearInterval(timer);
}
},20);
}
offsetLeft在取值时会进行四舍五入(原因是,像素的小数是没有意义的)
网友评论