解决了div框不能够准确到达指定位置的情况,出现这种情况的原因是当到快要到终点时,速度跳过一个单位,超过指定位置,再回来,又小于指定位置,所以不停的在指定位置跳转
解决方法:当最后的距离小于速度值时,直接将位置变为参数值。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
#div1{width:100px; height:150px; position:absolute; background:#0F0; left:500px;
top:20;}
#div2{width:1px; height:300px; left:100px; background:#00F; position:absolute; top:0px;}
#div3{width:1px; height:300px; left:300px; background:#00F; position:absolute; top:0px;}
</style>
<script>
window.onload=function()
{
var oDiv=document.getElementById(‘div1‘);
var oBtn1=document.getElementById(‘btn1‘);
var oBtn2=document.getElementById(‘btn2‘);
var speed;
oBtn1.onclick=function()
{
onmove(100);
}
oBtn2.onclick=function()
{
onmove(300);
}
var timer;
function onmove(iTarget)//带参数的方法
{
clearInterval(timer);//关闭所有定时器
timer=setInterval(function()//定义定时器
{
if(oDiv.offsetLeft<iTarget)//如果离左边的位置小于参数,速度为正
{
speed=7;
}
else//否则为负
{
speed=-7;
}
if(Math.abs(oDiv.offsetLeft-iTarget)<7)//如果距离小于7进行此操作
{
clearInterval(timer);//关闭定时器
oDiv.style.left=iTarget;//让其位置就是参数值
}
else
{
oDiv.style.left=oDiv.offsetLeft+speed+‘px‘;//进行匀速运动
}
},30)
}
}
</script>
</head>
<body>
<input id="btn1" type="button" value="到100" />
<input id="btn2" type="button" value="到300" />
<div id="div1">
</div>
<div id="div2">
</div>
<div id="div3">
</div>
</body>
</html>
原文:http://www.cnblogs.com/lzzhuany/p/4534764.html