效果:
思路:
利用setInerval()計時器,進行運動。然后關鍵的一點是在最后停止的時候給它一個填充縫隙的判斷。
代碼:
復制代碼 代碼如下:
<head runat="server">
<title></title>
<style type="text/css">
#div1
{
width: 100px;
height: 100px;
background: #0000FF;
position: absolute;
left: 800px;
top: 100px;
}
#div200
{
width: 1px;
height: 400px;
background: #FF0000;
position: absolute;
left: 200px;
}
#div500
{
width: 1px;
height: 400px;
background: #FF0000;
position: absolute;
left: 500px;
}
</style>
<script type="text/javascript">
function move(end) {
var oDiv = document.getElementById('div1');
var timer = null;
timer = setInterval(function () {
var speed = (end - oDiv.offsetLeft) / 5; //根據終點和offsetLeft取出運動的速度
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); //進位取整,小數位變為整位,
// if (oDiv.offsetLeft <= end) {
// clearInterval(timer);
// }
// else {
// oDiv.style.left = oDiv.offsetLeft + speed + 'px';
// }
if (Math.abs(end - oDiv.offsetLeft) <= speed) { //由于在停止的時候最后會出現小的縫隙,或者說沒有完全的到達指定地點,所以要小于它的速度
clearInterval(timer); //當距離小于速度時,讓計時器停止
oDiv.style.left = end + 'px'; //在停止后填充縫隙。
}
else {
oDiv.style.left = oDiv.offsetLeft + speed + 'px'; //移動DIV
}
}, 30)
}
</script>
</head>
<body>
<input type="button" value="到500的位置" />
<input type="button" value="到200的位置" />
<div>
</div>
<div>200
</div>
<div>500
</div>
</body>
新聞熱點
疑難解答
圖片精選