我有一个从盒子左上角开始的球,当您单击按钮时,它会移动到右下角。当达到 350px 时停止
我希望它在到达右下角后再上升到右上角。但如果我复制粘贴 IfElse 语句,那么 If(pos=350) 将立即运行该代码,而不是在 Else 处进行移动
这有道理吗
function animation() {
let id = null;
const ball = document.getElementById("ball");
let pos = 0;
id = setInterval(movement, 5);
function movement() {
if (pos == 350) {
clearInterval(id);
ball.style.background = "green";
} else {
ball.style.background = "red";
pos++;
ball.style.top = pos + "px";
ball.style.left = pos + "px";
}
}
}
#box {
width: 400px;
height: 400px;
margin-top: 20px;
position: relative;
background: yellow;
}
#ball {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
border-radius: 100%;
}
<button onclick="animation()">Click Here</button>
<div id ="box">
<div id ="ball"></div>
</div>
timeout
在动画中的使用并不理想。但让我们重点关注编程部分。基本上我添加了 directionX
和 directionY
作为位置增量。还通过为方向创建一个路线数组来进行一些概括。
function animation() {
let id = null;
const ball = document.getElementById("ball");
let posX = 0;
let posY = 0;
var routes = [{
dx: 1,
dy: 1,
},
{
dx: 0,
dy: -1,
},
{
dx: -1,
dy: 0,
}
]
function nextStep(step, posX, posY) {
if (step == 0 && posX == 350) {
return 1
}
if (step == 1 && posY == 0) {
return 2
}
if (step == 2 && posX == 0) {
return -1
}
return step;
}
var step = 0
id = setInterval(movement, 5);
function movement() {
step = nextStep(step, posX, posY)
if (step == -1) {
clearInterval(id);
return
}
var directionX = routes[step].dx
var directionY = routes[step].dy
ball.style.background = "red";
posX += directionX
posY += directionY
ball.style.top = posY + "px";
ball.style.left = posX + "px";
}
}
#box {
width: 400px;
height: 400px;
margin-top: 20px;
position: relative;
background: yellow;
}
#ball {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
border-radius: 100%;
}
<button onclick="animation()">Click Here</button>
<div id="box">
<div id="ball"></div>
</div>