gpt4 book ai didi

javascript - 将元素移动到右侧然后返回到左侧

转载 作者:行者123 更新时间:2023-11-28 13:25:39 25 4
gpt4 key购买 nike

简而言之,我想将一个元素移动到右侧,当到达右侧时,再次回到左侧,依此类推(“例如:将球击到墙上,然后它再次回到你身边”)

但是移动元素时出现错误!

The Code

var Ball = document.getElementById('ball');
var ballPosition = 0;

var pageWidth = document.body.offsetWidth;

var Loop = setInterval(function () {
ballPosition = Ball.offsetLeft;

if (ballPosition < pageWidth) {
Ball.style.left = ballPosition + 10 + "px";
} else {
Ball.style.left = ballPosition - 10 + "px";
}
}, 1000 / 60);
<div id="ball" style="width:70px; height:70px; margin:0; padding:0; border-radius:50px; position:absolute; background-color:#ff0000"> </div>

最佳答案

您可以尝试使用 ballSpeed 变量,并在到达左侧或右侧时将其乘以 -1:

var ball = document.getElementById('ball'),
ballPosition = 0,
ballSpeed = 10,
pageWidth = document.body.offsetWidth - ball.offsetWidth;
setInterval(function() {
ball.style.left = (ballPosition += ballSpeed) + 'px';
if (ballPosition <= 0 || ballPosition >= pageWidth) {
ballSpeed *= -1;
}
}, 1000 / 60);
#ball {
width: 70px;
height: 70px;
border-radius: 50px;
position: absolute;
background-color: #ff0000;
}
<div id="ball"></div>

关于javascript - 将元素移动到右侧然后返回到左侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29452664/

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