javascript實(shí)現(xiàn)左右緩動動畫函數(shù)
本文實(shí)例為大家分享了js實(shí)現(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){
// 清除定時(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 + "每次移動的步數(shù):" + step);
},20);
}
</script>
</body>
</html>

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

