动画的移动效果
程序员文章站
2022-05-02 20:06:10
...
*{margin: 0;}
div {
width: 100px;
height: 100px;
background-color: red;
position: relative;
margin-bottom: 30px;
}
<input type="button" id="btn1" value="click 800">
<input type="button" id="btn2" value="click 400">
<div id="box1"></div>
<div id="box2"></div>
<script>
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
var box1 = document.getElementById('box1');
var box2 = document.getElementById('box2');
btn1.onclick = function () {
animate(box1, 800);
animate(box2, 800);
}
btn2.onclick = function () {
animate(box1, 400);
animate(box2, 400);
}
function animate (element,target) {
if(element.timeid){
clearInterval(element.timeid);
}
element.timeid = setInterval(function () {
var current = element.offsetLeft;
var step = 10;
if(current>target){
step = -Math.abs(step);
}
if(Math.abs(current-target)<Math.abs(step)){
clearInterval(element.timeid);
element.style.left = target + 'px';
return;
}
current +=step;
element.style.left = current + 'px';
},30);
}
</script>
下一篇: Vue3实现过度动画效果