javascript实现左右缓动动画函数
(编辑:jimmy 日期: 2025/10/26 浏览:3 次 )
本文实例为大家分享了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 "目标位置:" + target + "当前位置:" + current + "每次移动的步数:" + step);
},20);
}
</script>
</body>
</html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇:JavaScript缓动动画函数的封装方法
