效果:
思路:
利用setInerval()計時器,進行運動。然後關鍵的一點是在最後停止的時候給它一個填滿縫隙的判斷。
代碼:
複製代碼代碼如下:
<head runat="server">
<title></title>
<style type="text/css">
#div1
{
width: 100px;
height: 100px;
background: #0000FF;
position: absolute;
left: 800px;
頂: 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" id="btn1" value="到500的位置" onclick="move(500);" />
<input type="button" id="btn2" value="到200的位置" onclick="move(200);" />
<div id="div1">
</div>
<div id="div200">200
</div>
<div id="div500">500
</div>
</body>