Compared with Prinuse animation than the callback hell, the code more readable
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
width: 200px;
height: 300px;
background-color: rebeccapurple;
position: absolute;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
// el 元素
// attr 样式
// val 目标样式的具体指
//cd 当前动画结束后,要做的事情
function move(el,attr,val){
//当前值
let now = parseFloat(getComputedStyle(el)[attr]);
//方向/速度 abs 取绝对值 最后得出结果 -1 或 1表示方向
let speed = (val - now) / Math.abs(val - now) *2;
return new Promise((resolve)=>{ // 新建一个对象
clearInterval(el.timer);
el.timer = setInterval(()=>{ //el 元素 元素上挂载定时器
if(Math.abs(now - val) <= 0){
clearInterval(el.timer);
resolve();
// cb && cb(); //就是做一个判断 当前动画结束之后要做的动作
}else{
now += speed; //获取当前值 + 方向/速度
// console.log(now)
el.style[attr] = now + "px"; //给元素赋值赋值
}
},20)
}) //return
}
{
let box = document.querySelector(".box");
function boxMove(){
//使用Promise 完成回调
move(box,"left",200).then(()=>{
return move(box,"top",200) //这行prm对象的状态就是上一个对象的状态,第三种情况
}).then(()=>{
return move(box,"left",0)
}).then(()=>{
return move(box,"top",0)
}).then(()=>{
boxMove();
})
}
boxMove();
}
</script>
</body>
</html>