<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>简易运动</title>
<style>
#box{
width: 200px;
height: 200px;
background: red;
position: absolute;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
/*
el 元素
attr 样式
val 目标样式的 具体值
cb 当前动画结束后,要做的事情
*/
function move(el,attr,val){
//当前值
let now = parseFloat(getComputedStyle(el)[attr]);
// 速度/方向
let speed = (val - now) / Math.abs(val - now) *2;
return new Promise((resolve)=>{
clearInterval(el.timer);
el.timer = setInterval(() => {
if(Math.abs(now-val) <= 0){
clearInterval(el.timer);
resolve();
}else{
now += speed;
el.style[attr] = now + "px";
}
}, 20);
});
}
{
let box = document.querySelector("#box");
//使用Promise 来完成回调
function boxMove(){
move(box,"left",200).then(()=>{
return move(box,"top",200)
}).then(()=>{
return move(box,"left",0);
}).then(()=>{
return move(box,"top",0);
}).then(()=>{
boxMove();
});
}
boxMove();
}
</script>
</body>
</html>
promise动画
最新推荐文章于 2022-02-11 20:02:54 发布