具體分析如下:
該實(shí)例可實(shí)現(xiàn)一開始速度很快,然后慢下來,直到停止的效果。
要點(diǎn):
var speed = (target-box.offsetLeft)/8;
目標(biāo)點(diǎn)減去元素的當(dāng)前位置的值除以8,因?yàn)閛ffsetleft的值是一直在變大,所以速度的值也是一直的變小
speed = speed>0?Math.ceil(speed):Math.floor(speed);
正向速度的時(shí)候向上取整,反向速度的時(shí)候向下取整
代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312" />
<title>無標(biāo)題文檔</title>
<style>
<!--
body{margin:0; padding:0; font:12px/1.5 arial;}
#box{width:100px; height:100px; position:absolute;
background:#06c; left:0;}
-->
</style>
<script>
<!--
window.onload = function(){
var box = document.getElementById("box");
var btn = document.getElementById("btn");
var timer=null;
btn.onclick = function(){
startrun(300);
}
function startrun(target){
clearInterval(timer);
timer = setInterval(function(){
var speed = (target-box.offsetLeft)/8;
speed = speed>0?Math.ceil(speed):Math.floor(speed);
if(box.offsetLeft == target){
clearInterval(timer);
}else{
box.style.left = box.offsetLeft+speed+"px";
}
document.getElementById('abc').innerHTML+=box.offsetLeft+','+speed+'<br>';
},30);
}
}
//-->
</script>
</head>
<body>
<input id="btn" type="submit" value="向右運(yùn)動(dòng)">
<div id="box">
</div>
<br>
<textarea id="abc" cols="50" rows="10"
style="margin-top:130px"></textarea>
</body>
</html>
更多信息請(qǐng)查看IT技術(shù)專欄