您好,我想多次将 img 插入到 div 中,每次我的 img 都会有不同的属性。我的 Html 代码将有一个带有名为 ID_DIV 的示例 ID 的 div。 我将在 html 代码中添加一个样式部分,例如 img position absolute。
我会根据我需要的img数量预设变量NumberOfTimes到div中。
但我无法使循环正常工作。每次我刷新浏览器时,我的 img 都会出现在不同的位置,但不会出现“NumberOfTImes”次。 我已经将我的代码编辑成这个。但是循环无论如何都不起作用。仍然不知道它是什么。
function generateImg(){
var numberOfTimes=prompt("how many times?");
var div_id1=document.getElementById("div_id1");
do{
var oImg=document.createElement("img"); // Creates an oimg node
oImg.setAttribute('src', 's0me_s0urce'); // sets the source for img file
div_id1.appendChild(oImg); // append the img to #id Div.
document.querySelector('img').style.top = Math.floor(Math.random()*401)+'px';
document.querySelector('img').style.left = Math.floor(Math.random()*401)+'px';
numberOfTimes--;
}while(numberOfTimes>0);
}
请帮助。我找不到这个逻辑的错误在哪里。
最佳答案
您需要在循环外声明“i”,否则它不会递减,只会是“NumberOfTimes - 1”,因此您的循环将在同一位置循环重复图像。这也假设“NumberOfTimes”在首先使用的相同范围内。请注意,我已经移动了“i”的位置并在循环中为其添加了一个递减值。
function RandomPositionImgs(){
var i=NumberOfTimes;
do{
var oImg=document.createElement("img"); // Creates an oimg node
oImg.setAttribute('src', 'some_source'); // sets the source for img file
document.getElementById("ID_DIV").appendChild(oImg); // append the img to leftSide Div.
document.querySelector('img').style.top = Math.floor(Math.random()*401)+'px'; // random positioning
document.querySelector('img').style.left = Math.floor(Math.random()*401)+'px'; // random positioning
i--;
}while(i>0);
}
关于javascript - 如何使用循环多次将 img 插入到 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36673026/