gpt4 book ai didi

javascript - 如何在 setInterval() 中停止递归。 Javascript

转载 作者:行者123 更新时间:2023-11-30 14:53:25 26 4
gpt4 key购买 nike

<!DOCTYPE html>
<html>
<title>test</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<style>
.mySlides {display:none;}
</style>
<body>

<h2 class="w3-center">Slideshow test</h2>

<div class="w3-content w3-section" style="max-width:500px">
<img class="mySlides" src="1.jpg" style="width:100%">
<img class="mySlides" src="2.jpg" style="width:100%">
<img class="mySlides" src="3.jpg" style="width:100%">
<img class="mySlides" src="4.jpg" style="width:100%">
</div>

<p id="demo"><p>

<script>
var Index = 0;
var x = document.getElementsByClassName("mySlides");

(Index <4) ? setInterval(slide,500):display(Index-1);


function slide() {
var i;
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
Index++;
document.getElementById('demo').innerHTML = Index-1;
x[Index-1].style.display = "block";
}

function display(n) {
x[n].style.display = "block";
}
</script>

</body>
</html>

我想通过 setInterval() 显示一系列图像。最后,应该显示最后一张图像。问题是运行后没有图像。我确定变量 'Index' 仍然保持增加 1。我不知道为什么....

最佳答案

您的代码需要clearInterval 方法来停止interval。出于演示目的,我已将您的 images 替换为 divs

var index = 0;
var x = document.getElementsByClassName("mySlides");

function displayNextSlide() {
for (var i = 0; i < x.length; i++) {
if (i === index) {
x[i].style.display = "block";
} else {
x[i].style.display = "none";
}
}
index++;
if (index == x.length) {
clearInterval(interval);
}
}
displayNextSlide();
var interval = setInterval(displayNextSlide, 500)
<!DOCTYPE html>
<html>
<title>test</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<style>
.mySlides {
display: none;
}
</style>

<body>

<h2 class="w3-center">Slideshow test</h2>

<div class="w3-content w3-section" style="max-width:500px">
<div class="mySlides" src="1.jpg" style="width:100%">1</div>
<div class="mySlides" src="2.jpg" style="width:100%">2</div>
<div class="mySlides" src="3.jpg" style="width:100%">3</div>
<div class="mySlides" src="4.jpg" style="width:100%">4</div>
</div>

关于javascript - 如何在 setInterval() 中停止递归。 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47776729/

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