JavaScript基础学习 缓动动画多个值移动
Document
div{
position: absolute;
width: 100px;
height: 100px;
background-color: pink;
left: 0;
}
span{
position: absolute;
width:200px;
height: 200px;
top: 200px;
left: 0;
background-color: purple;
}
启动第二个
2222
var div =document.querySelector('div');
var span=document.querySelector('span');
var btn =document.querySelector('button');
// 给不同元素指定不同的定时器
function move(obj,target){
// 想要调用定时器时首先就需要清除已有的定时器,然后再重新启动
clearInterval(obj.timer);
obj.timer=setInterval(function(){
var step =(target-obj.offsetLeft)/10;
step =Math.ceil(step);
if(obj.offsetLeft >= target){
clearInterval(obj.timer);
console.log(22222222222);
}else{
obj.style.left=obj.offsetLeft + step + 'px';
}
},30)
}
// 当我们多次点击按钮时,此时的定时器会叠加多个导致加快
// 解决方案: 在调用定时器函数当中第一步就将定时器清除
btn.addEventListener('click',function(){
move(span,500);
})