用js實現緩沖運動效果


效果如下,一開始速度很快,然后慢下來,直到停止。

 


 

要點:

var speed = (target-box.offsetLeft)/8;    目標點減去元素的當前位置的值除以8,因為offsetleft的值是一直在變大,所以速度的值也是一直的變小
speed = speed>0?Math.ceil(speed):Math.floor(speed);  正向速度的時候向上取整,反向速度的時候向下取整

 

上代碼

<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312" />
<title>無標題文檔</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="向右運動">
<div id="box">
</div>
<br>
<textarea id="abc" cols="50" rows="10" style="margin-top:130px"></textarea>
</body>
</html>




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM