1. 程式人生 > 其它 >java script實現基礎的緩動動畫

java script實現基礎的緩動動畫

技術標籤:javascripthtmlcss

方塊右移動畫的實現,移動速度逐漸降低。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <
style> div { position: absolute; width: 100px; height: 100px; background-color: pink; } .button-500 { margin-top:300px; } .button-800 { margin-top:350px; } </style> </head> <
body> <div></div> <button class="button-500">點選開啟運動到500</button> <button class="button-800">點選開啟運動到800</button> <script> var div=document.querySelector('div'); var button1=document.querySelector('.button-500'); var
button2=document.querySelector('.button-800'); //封裝函式 function animate(obj,target,callback){ //先清除一次定時器,防止點選按鈕時重複呼叫 clearInterval(obj.timer); obj.timer=setInterval(function() { var step=(target-obj.offsetLeft)/10; //js中出現小數會有誤差,所以去除誤差的方法就是向上取整 //兩個是因為當往回走的時候也需要判斷位置 step=step>0?Math.ceil(step):Math.floor(step); if(div.offsetLeft==target){ clearInterval(obj.timer); //設定一個回撥函式判斷,如果有回撥函式,則執行回撥函式 if(callback){ callback(); } } obj.style.left=obj.offsetLeft+step+'px'; }, 15); } //呼叫函式直接可以實現動畫 button1.addEventListener('click',function(){ animate(div,500); }) button2.addEventListener('click',function(){ animate(div,800,function(){//設定回撥函式 div.style.backgroundColor='red'; }); }) </script> </body> </html>

(學習於黑馬的pink老師,相似之處還請見諒。)