JS實現(xiàn)勻速運動的代碼實例
更新時間:2013年11月29日 16:45:42 作者:
這篇文章主要介紹了JS實現(xiàn)勻速運動的代碼實例,有需要的朋友可以參考一下
效果:
思路:
利用setInerval()計時器,進行運動。然后關(guān)鍵的一點是在最后停止的時候給它一個填充縫隙的判斷。
代碼:
復制代碼 代碼如下:
<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; //根據(jù)終點和offsetLeft取出運動的速度
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); //進位取整,小數(shù)位變?yōu)檎唬?BR> // if (oDiv.offsetLeft <= end) {
// clearInterval(timer);
// }
// else {
// oDiv.style.left = oDiv.offsetLeft + speed + 'px';
// }
if (Math.abs(end - oDiv.offsetLeft) <= speed) { //由于在停止的時候最后會出現(xiàn)小的縫隙,或者說沒有完全的到達指定地點,所以要小于它的速度
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>
相關(guān)文章
一篇文章搞定JavaScript類型轉(zhuǎn)換(面試常見)
這篇文章主要介紹了一篇文章搞定JavaScript類型轉(zhuǎn)換(面試常見),非常不錯,具有參考借鑒價值,需要的朋友參考下吧2017-01-01

