JavaScript基础学习 缓动动画中的回调函数
移动到指定位置之后span标签的背景颜色会变动
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: yellow;
}
启动第二个到500
启动第二个到800
2222
var div =document.querySelector('div');
var span=document.querySelector('span');
var btn500 =document.querySelector('.btn500');
var btn800 =document.querySelector('.btn800');
// 给不同元素指定不同的定时器
function move(obj,target,callback){
// 想要调用定时器时首先就需要清除已有的定时器,然后再重新启动
clearInterval(obj.timer);
obj.timer=setInterval(function(){
var step =(target-obj.offsetLeft)/10;
// step =Math.ceil(step);
step = step>0 ? Math.ceil(step):Math.floor(step);
if(obj.offsetLeft == target){
clearInterval(obj.timer);
console.log(22222222222);
// 回调函数写在定时器之后,在定时器停止之后执行该函数
if(callback){
callback();
}
}else{
obj.style.left=obj.offsetLeft + step + 'px';
}
},30)
}
// 当我们多次点击按钮时,此时的定时器会叠加多个导致加快
// 解决方案: 在调用定时器函数当中第一步就将定时器清除
btn500.addEventListener('click',function(){
move(span,500);
})
btn800.addEventListener('click',function(){
move(span,800,function(){
span.style.backgroundColor='red';
});
})