javascript實(shí)現(xiàn)左右緩動(dòng)動(dòng)畫函數(shù)
更新時(shí)間:2020年11月25日 12:59:12 作者:persistsss
這篇文章主要為大家詳細(xì)介紹了javascript實(shí)現(xiàn)左右緩動(dòng)動(dòng)畫函數(shù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
本文實(shí)例為大家分享了js實(shí)現(xiàn)左右緩動(dòng)動(dòng)畫函數(shù)的封裝代碼,供大家參考,具體內(nèi)容如下
<!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">移動(dòng)400px</button> <button class="btn2">移動(dòng)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); } // 緩動(dòng)動(dòng)畫 function animate(element,target){ // 清除定時(shí)器 clearInterval(element.timeId); element.timeId = setInterval(function(){ // 獲取元素當(dāng)前的位置 let current = element.offsetLeft; // 當(dāng)current越大,step越小,先快后慢 let step = (target - current) / 10; // 當(dāng)step大于0時(shí),step向上取整,否則,step向下取整 step = step > 0 ? Math.ceil(step) : Math.floor(step); current += step; element.style.left = current + 'px'; // 不用擔(dān)心到達(dá)不了目標(biāo)位置,因?yàn)閟tep最小達(dá)到1 if(current == target){ clearInterval(element.timeId); } console.log("目標(biāo)位置:" + target + "當(dāng)前位置:" + current + "每次移動(dòng)的步數(shù):" + step); },20); } </script> </body> </html>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
簡(jiǎn)單談?wù)凧S數(shù)組中的indexOf方法
最近在工作中遇到一個(gè)小問題,這篇文章代碼我會(huì)簡(jiǎn)化成小例子展示給大家。給大家詳細(xì)的介紹JS數(shù)組中的indexOf方法,用心看到最后會(huì)有收獲哈,有需要的朋友們下面來一起看看吧。2016-10-10JS中mouseover和mouseout多次觸發(fā)問題如何解決
這篇文章主要介紹了JS中mouseover和mouseout多次觸發(fā)問題如何解決的相關(guān)資料,非常不錯(cuò)具有參考借鑒價(jià)值,需要的朋友可以參考下2016-06-06針對(duì)JavaScript中this指向的簡(jiǎn)單理解
這篇文章主要為大家詳細(xì)JavaScript中this指向的簡(jiǎn)單理解,感興趣的小伙伴們可以參考一下2016-08-08JavaScript中sharedWorker 實(shí)現(xiàn)多頁(yè)面通信的實(shí)例詳解
這篇文章主要介紹了JavaScript中sharedWorker 實(shí)現(xiàn)多頁(yè)面通信,通過給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04