gpt4 book ai didi

javascript - 如何在到达某个位置时激活间隔?

转载 作者:行者123 更新时间:2023-12-02 23:31:40 27 4
gpt4 key购买 nike

问题是它同时调用了 var intervalLeftintervaRight 。当它向右移动时,我希望 intervalLeft 不起作用,反之亦然。当它达到 startPosition 100 时,它会激活 intervalLeft;当它达到 startPosition 0 时,它会激活 intervalRight 无限。

<div id="moveAnimation" class="block"></div>
</div>
<script>
var elem = document.getElementById("moveAnimation");
elem.addEventListener("click", movingImage);

function movingImage() {
var startPosition = 0;
var intervalRight = setInterval(frameRight, 10);
var intervalLeft = setInterval(frameLeft, 10);

function frameRight() {
if (startPosition >= 100) {
clearInterval(intervalRight);
frameLeft();
} else {
startPosition += 0.5;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}

function frameLeft() {
if (startPosition <= 0) {
clearInterval(intervalRight);
frameRight();
} else {
startPosition -= 2;
document.getElementById("moveAnimation").style.right = startPosition + "%";
}
}
}
</script>

这是练习:

在此之下,您有一个 div 需要使用 JS 进行从左到右的移动。使其在2秒内到达终点,然后在5秒内返回。永远重复这一点。

最佳答案

已更新您的代码。使用如下

<div id="moveAnimation" class="block"></div>
</div>
<script>
var elem = document.getElementById("moveAnimation");
elem.addEventListener("click", movingImage);



function movingImage() {
var startPosition = 0;
var intervalRight = setInterval(frameRight, 10);
var rightTimer = true;
var leftTimer = false;
var intervalLeft;

function frameRight() {
if(!rightTimer){
rightTimer = true;
intervalRight = setInterval(frameRight,10)
return;
}
if (startPosition >= 100) {
rightTimer = false;
clearInterval(intervalRight);
frameLeft();

} else {

startPosition += 0.5;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}

}

function frameLeft() {
if(!leftTimer){
leftTimer = true;
intervalLeft = setInterval(frameLeft,10)
return;
}
if (startPosition <= 0) {
leftTimer = false;
clearInterval(intervalLeft);
frameRight();

} else {

startPosition -= 2;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
}
</script>

关于javascript - 如何在到达某个位置时激活间隔?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56473319/

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