这是幻灯片。
delayLoop
打开和关闭容器,有效。问题是 myFunc01
不会等待 delayLoop
完全执行。 console.log
仅供我参考。
while
循环的存在只是为了让for
循环不会结束。有人可以帮我解决我的逻辑或找到另一种方法让幻灯片无尽吗?
function delayLoop() {
document.getElementById("news-1").style.display = "flex";
for (let i = 1; i < 4; i++) {
setTimeout(function() {
let u = i - 1;
document.getElementById("news-" + i).style.display = "flex";
document.getElementById("news-" + u).style.display = "none";
}, i * 5000);
}
}
var myFunc01 = function() {
var i = 0;
while (i < 100) {
(function(i) {
setTimeout(function() {
delayLoop();
console.log("ok");
}, 1000 * i)
})(i++)
}
};
myFunc01();
不幸的是,您的实施存在许多问题。首先,setTimeout 是异步的,这意味着它不会等待它完成才继续执行代码。这样做的结果是 for 循环立即运行所有条目,并将它们全部排队等待立即执行,这意味着所有内容基本上都会在 1 秒内运行。
其次,由于 setTimeout 中使用的函数的性质,因此存在 closures 的概念(稍后会查找)。这意味着setTimeout中函数内i的内容将始终为1,而不是1然后2然后3等。
我想说,互联网上有很多幻灯片实现可供使用,而不是自己滚动,因此可能值得一看。
但是,考虑到您正在自己动手学习,请考虑以下事项:
我假设你有一个像这样的元素:
<div>
<div class="news showing">
First slide
</div>
<div class="news">
Second slide
</div>
<div class="news">
Third slide
</div>
</div>
您可以使用CSS来控制显示和隐藏:
.news {
display: none
}
.news.showing {
display: flex
}
然后使用setInterval,而不是setTimeout(因为setTimeout只运行一次):
const interval = setInterval(() => {
const elements = Array.from(document.querySelectorAll('.news'))
let nextElement
/**
* Iterate through the entries, checking if they have the showing class.
* If they do, remove the class, and grab the next element (this will either be the next in the
* array, or the first element if we're already at the last news entry)
*/
elements.forEach((el, index) => {
if(Array.from(el.classList).includes("showing")) {
el.classList.remove('showing') //Remove the class to hide this
nextElement = elements[index+1]!==undefined ? elements[index+1] : elements[0]//Grab next one
}
});
nextElement.classList.add("showing");//Add the showing class to the next one so it shows.
}, 1000)