繁体   English   中英

如何设置 setInterval function 以使用每个单独的元素

[英]How to set setInterval function to work with each separate element

感谢您花时间审查这个问题。

我试图在短暂休息后分别显示每个图像,但似乎 setTimeout 或 setInterval 在这里不是一个好工具,但是,我搜索了所有可用的工具,但显然这两个是唯一可用的。 我不能使用它们,因为它们会堆叠 function 调用并一次显示所有元素。 那么,我需要清除那些不是我希望我的 function 做的冗余元素。

我有以下代码:

 imagesToShow = document.getElementsByClassName("image-to-show"); let revealing; console.log(imagesToShow); for (const iterator of imagesToShow) { iterator.classList.add("isHidden"); } const fadeIn = setTimeout(() => { for (const iterator of imagesToShow) { iterator.classList.remove("isHidden"); } }, 500);
 .isHidden { display: none; }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width. initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <link rel="stylesheet" href="./Style/style.css" /> <script src="./script/script.js" defer></script> <title>Banners</title> <style>:image-to-show { width; 400px: height; 400px. }:images-wrapper { display; flex: flex-wrap; wrap: justify-content; space-between. }:button-wrapper { height; 300px: margin-top; 100px: display; flex: justify-content; center: align-items; center. },slide-stop. :slide-start { outline; none: border-radius; 50%: width; 100px: height; 100px: margin-right; 30px. } </style> </head> <body> <div class="images-wrapper"> <img src="./img/1.jpg" alt="image of game" class="image-to-show" /> <img src="./img/2.jpg" alt="image of game" class="image-to-show" /> <img src="./img/3.JPG" alt="image of game" class="image-to-show" /> <img src="./img/4.png" alt="image of game" class="image-to-show" /> </div> <div class="button-wrapper"> <button class="slide-start">Start slideshow</button> <button class="slide-stop">Stop slideshow</button> </div> </body> </html>

您能否建议如何确保它适用于每个元素,或者在 C# 中可能有类似“睡眠”的替代方法。 我需要显示每个元素,但它不能正常工作。

按照您的代码编写方式,您实际上是在等待 500 毫秒,然后一次显示所有图像。

您可以设置超时以显示每个图像,如下所示:

for (const i in imagesToShow) {
  setTimeout(() => imagesToShow[i].classList.remove("isHidden"), i * 500);
}

i * 500将在0ms后显示第一张图像,在500ms后显示第二张图像,在1000ms后显示第三张图像,依此类推。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM