簡體   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