代码及运行效果也可在 jsbin 中查看:https://jsbin.com/tilolazaci/1/edit?html,js,output
其中主要的代码是这两行:
//表达的意思是每调用一次定时器,box移动的距离为剩下路程的1/10。
var speed = (iTarget - box.offsetLeft)/10;
//对speed向上取整,以确保.box能准确运行到目标位置,如果没有这行代码,.box会在到达目标位置前停止运动.
//但如果添加了这行代码,是否会产生让运动物体越过目标位置的bug呢?
speed = Math.ceil(speed);
疑问:是否存在向上取整后,最终得到的speed值大于剩余路程(iTarget - box.offsetLeft)的值的可能性?
如果会大于,那么.box运动的距离会超过目标位置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<input type="button" class="run" value="开始运动" />
<!-- 运动物体 -->
<div class="box"></div>
<!-- 目标位置-->
<div class="target"></div>
</body>
</html>
var box = document.querySelector(".box"),
run = document.querySelector(".run");
run.addEventListener("click",function(){
setInterval(function(){
//目标位置
var iTarget = 300;
var speed = (iTarget - box.offsetLeft)/10;
//如果没有对speed向上取整时,.box无法准确到达目标点
speed = Math.ceil(speed);
box.style.left = box.offsetLeft + speed + "px";
},30);
});
/* 运动物体 */
.box{
position:absolute;
left:0;
top:50px;
width:100px;
height:100px;
background-color: red;
}
/* 目标位置 */
.target{
position:absolute;
left:300px;
top:0;
width:1px;
height:300px;
background-color: blue;
}