javascript實現(xiàn)左右緩動動畫函數(shù)
更新時間:2020年11月25日 12:59:12 作者:persistsss
這篇文章主要為大家詳細介紹了javascript實現(xiàn)左右緩動動畫函數(shù),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了js實現(xiàn)左右緩動動畫函數(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">移動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 + "每次移動的步數(shù):" + step);
},20);
}
</script>
</body>
</html>

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Javascript 事件捕獲的備忘(setCapture,captureEvents)
Javascript 事件捕獲的備忘(setCapture,captureEvents)...2006-09-09
JS/jQuery實現(xiàn)默認顯示部分文字點擊按鈕顯示全部內(nèi)容
默認顯示部分文字,點擊按鈕顯示全部,類似這樣的功能在一些特殊的地方會見到吧,下面與大家分享下JS、jQuery如何實現(xiàn),感興趣的朋友可以參考下哈,希望對你有所幫助2013-05-05
原生態(tài)js,鼠標按下后,經(jīng)過了那些單元格的簡單實例
下面小編就為大家?guī)硪黄鷳B(tài)js,鼠標按下后,經(jīng)過了那些單元格的簡單實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08
JS實現(xiàn)將對象轉(zhuǎn)化為數(shù)組的方法分析
這篇文章主要介紹了JS實現(xiàn)將對象轉(zhuǎn)化為數(shù)組的方法,結(jié)合實例形式分析了javascript操作及轉(zhuǎn)換json數(shù)組相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2019-01-01
在Z-Blog中運行代碼[html][/html](純JS版)
在Z-Blog中運行代碼[html][/html](純JS版)...2007-03-03

