gpt4 book ai didi

javascript - 我怎样才能把盒子移到拐 Angular 处

转载 作者:行者123 更新时间:2023-11-30 11:00:41 27 4
gpt4 key购买 nike

我想移动拐 Angular 处的方框(从左上角开始水平移动 Angular 落到右上角然后你去到右下角。

function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);

function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}

#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
<p><button onclick="myMove()">Click Me</button></p>

<div id="container">
<div id="animate"></div>
</div>

最佳答案

你可以如下设置topleft的距离,让它每次都在一个方向上移动,并在总行进距离满足位置时停止:

function myMove() {
var elem = document.getElementById("animate");
var left = 0;
var top = 0;
var id = setInterval(frame, 5);
elem.style.left = "0px";
elem.style.top = "0px"

function frame() {
if (left < 350 && top == 0) {
left++;
elem.style.left = left + "px";
} else if (left == 350 && top < 350) {
top++;
elem.style.top = top + "px";
} else if (top == 350 && left > 0) {
left--;
elem.style.left = left + "px";
}
else {
clearInterval(id);
}
}
}
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}

#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
<p><button onclick="myMove()">Click Me</button></p>
<div id="container">
<div id="animate"></div>
</div>

关于javascript - 我怎样才能把盒子移到拐 Angular 处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57883296/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com