我正在尝试对脚本的每次迭代进行延迟,该脚本基于数组的元素生成动态 div,该数组具有一些指向图像的链接,以实现某种效果,如 GameCube 控制台介绍中的效果一个 div 一个一个地出现,而不是同时出现。
我试过 setTimeout() 和 Async 函数,但它们就是不起作用
var arraydas = ["aviso1.jpg","aviso2.jpg","a","s","s",2,3,4];
var array = ["sYDqBU1.jpg","t1LuvGZ.jpg","l660ATK.jpg","iNWWr7b.jpg"]
var htmlElements = "";
for (var i = 0; i < array.length; i++) {
htmlElements += '<div class="box"><img src="https://i.imgur.com/'+array[i]+'" width="100%" height="100%"></div>';
}
var container = document.getElementById("container");
container.innerHTML = htmlElements;
html,body {
width: 100%;
height: 100%;
}
#container {
height: 100%;
background-color: black;
}
.box {
width: 25%;
height: 25%;
background-color: red;
float:left;
}
<div id="container">
</div>
最佳答案
解决方案是使用计时器而不是循环。因为计时器会一遍又一遍地运行,所以它会产生循环效果,但还有一个额外的好处,那就是在你的时间尺度上这样做。
var array = ["sYDqBU1.jpg","t1LuvGZ.jpg","l660ATK.jpg","iNWWr7b.jpg"]
// This will keep track of the currently displayed array index
let counter = 0;
let container = document.getElementById("container");
function makeDiv(){
// If we've reached the end of the array, stop the timer
if(counter >= array.length-1) { clearInterval(timer); }
// Don't build HTML strings, create DOM elements
let div = document.createElement("div");
// Configure their properties
div.classList.add("box");
let img = document.createElement("img");
img.src = "https://i.imgur.com/" + array[counter];
// And append them to the DOM
div.appendChild(img);
container.appendChild(div);
// Increase the counter
counter++;
}
// Start the timer
let timer = setInterval(makeDiv, 1000);
html,body {
width: 100%;
height: 100%;
}
#container {
height: 100%;
background-color: black;
}
.box {
width: 25%;
height: 25%;
background-color: red;
float:left;
}
div > img { width:100%; }
<div id="container">
Hola kaskdkasdkasdk
</div>
关于javascript - 如何延迟在 JavaScript 上生成动态 div 数量的 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59002674/