简易运动
程序员文章站
2022-06-10 10:06:33
...
<!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>
</body>
</html>
el 元素
attr 样式
val 目标样式的 具体值
cb 当前动画结束后,要做的事情
<script>
function move(el,attr,val,cb){
//当前值
let now = parseFloat(getComputedStyle(el)[attr]);
// 速度/方向
let speed = (val - now) / Math.abs(val - now) *2;
el.timer = setInterval(() => {
if(Math.abs(now-val) <= 0){
clearInterval(el.timer);
cb && cb();
}else{
now += speed;
el.style[attr] = now + "px";
}
}, 20);
}
{
let box = document.querySelector("#box");
// 异步的 回调地狱
function BoxMove(){
move(box,"left",200,()=>{
// console.log("运动结束了");
move(box,"top",200,()=>{
move(box,"left",0,()=>{
move(box,"top",0);
});
});
});
}
}
</script>