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;
let step = (target - current) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
current += step;
element.style.left = current + 'px';
if(current == target){
clearInterval(element.timeId);
}
console.log("目标位置:" + target + "当前位置:" + current + "每次移动的步数:" + step);
},20);
}
</script>
</body>
</html>