<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>关于匀速运动的停止问题</title>
<style>
#div1{
width: 200px;
height: 200px;
position: absolute;
top: 100px;
left: 900px;
background: pink;
}
.div2{
width: 2px;
height: 600px;
position: absolute;
left:600px;
background: black;
}
.div3{
width: 2px;
height: 600px;
position: absolute;
left:200px;
background: black;
}
</style>
<script type="text/javascript">
window.onload=function(){
var oDiv=document.getElementById('div1');
}
function startMove(iTarget){
var oDiv=document.getElementById('div1');
var timer=null;
var speed=0;
timer=setInterval(function(){
if(oDiv.offsetLeft<iTarget){ //判断物体在目标的左边还是右边,以此来决定速度的方向
speed=7;
}else{
speed=-7;
};
if(Math.abs(iTarget-oDiv.offsetLeft)<=7){ //为了避免物体与目标之间的距离除速度除不尽,导致物体在目标附近闪烁
clearInterval(timer); //只要到达目标附近一个速度的距离,就关闭定时器
oDiv.style.left=iTarget+'px'; //并且手动让物体刚好到达目标
}
else{
oDiv.style.left=oDiv.offsetLeft+speed+'px';
}
},30);
};
</script>
</head>
<body>
<div id='div1'></div>
<div class='div2'></div>
<div class='div3'></div>
<button type="button" name="button" id='btn1' onclick='startMove(200)'>点我就到200</button>
<button type="button" name="button" id='btn2' onclick='startMove(600)'>点我就到600</button>
</body>
</html>
总的来说,匀速运动的终止条件满足以下两点即可实现在目标出精准停止:
1,距离足够近
2,手动拉到目标处