css:
#div{ position: absolute; left:800px; top:30px; background: yellowgreen; width:100px; height:100px; } #target{ width:1px; height:300px; background: black; position: absolute; left:300px; top:0; }html:
<!--终点线--> <div id="target"></div> <!--终点线--> <div id="div"></div> <input type="button" value="点击运动" id="btn">js:
var btn=document.getElementById("btn"); btn.onclick=function () { startMove(300) } var timer=null; var startMove=function (oTarget) { clearInterval(timer); var odiv=document.getElementById("div"); timer=setInterval(function () { var ispeed=(oTarget-odiv.offsetLeft)/8; ispeed>0?ispeed=Math.ceil(ispeed):ispeed=Math.floor(ispeed);//准确到达终点的位置 - 三目运算 // if(ispeed>0){ //准确到达终点的位置 // ispeed=Math.ceil(ispeed) // }else{ // ispeed=Math.floor(ispeed) // } if(odiv.offsetLeft<=oTarget){ clearInterval(timer); }else{ odiv.style.left=odiv.offsetLeft+ispeed+"px"; } },30) }