javascript實現左右緩動動畫函式
阿新 • • 發佈:2020-11-27
本文例項為大家分享了js實現左右緩動動畫函式的封裝程式碼,供大家參考,具體內容如下
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="bootstrap-4.4.1.css" > <style> .box{ width: 100px; height: 100px; background-color: chartreuse; position:absolute; } </style> </head> <body> <button class="btn1">移動400px</button> <button class="btn2">移動800px</button> <div class="box"></div> <script> let btn1 = document.querySelector('.btn1'); let btn2 = document.querySelector('.btn2'); let box = document.querySelector('.box'); btn1.onclick = function(){ animate(box,400); } btn2.onclick = function(){ animate(box,800); } // 緩動動畫 function animate(element,target){ // 清除定時器 clearInterval(element.timeId); element.timeId = setInterval(function(){ // 獲取元素當前的位置 let current = element.offsetLeft; // 當current越大,step越小,先快後慢 let step = (target - current) / 10; // 當step大於0時,step向上取整,否則,step向下取整 step = step > 0 ? Math.ceil(step) : Math.floor(step); current += step; element.style.left = current + 'px'; // 不用擔心到達不了目標位置,因為step最小達到1 if(current == target){ clearInterval(element.timeId); } console.log("目標位置:" + target + "當前位置:" + current + "每次移動的步數:" + step); },20); } </script> </body> </html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。