编辑:这是另一个问题:我无法用 for 循环定义每张图片的 Z-index
。
function placeImage(x) {
var div = document.getElementById("div_picture_right");
div.innerHTML = ""; // clear images
for (counter = 1; counter <= x; counter++ ) {
var image = document.createElement("img");
image.src = "borboleta/Borboleta" + counter + ".png";
image.width = "195";
image.height = "390";
image.alt = "borboleta" + counter;
image.id = "imagem" + counter;
image.position = "relative";
image.style.zIndex = counter;
div.appendChild(image);
}
};
window.onload = function () {
placeImage(20);
};
<body>
<div id="div_wrapper">
<div id="div_header">
<h1>First Project</h1>
</div>
<div id="div_picture">
<div id="div_picture_left"></div>
<div id="div_picture_right"></div>
</div>
</div>
</body>
检查 FireBug 时,我得到这个:
Error: image corrupt or truncated
最佳答案
看起来您的代码是在 div
出现在页面上之前执行的。在完全加载之前,您不应该尝试获取 DOM 中元素的句柄。您可以在 window.onload
之外定义您的函数,但将您的调用保持在 window.onload
内,例如:
function placeImage(x)
{
var div = document.getElementById("div_picture_right");
div.innerHTML = ""; // clear images
for (counter=1;counter<=x;counter++) {
var imagem=document.createElement("img");
imagem.src="borboleta/Borboleta"+counter+".png";
div.appendChild(imagem);
}
}
window.onload = function() {
placeImage(48);
};
我还添加了一个小改进,即获取 div
的句柄并存储在变量中一次,而不是每次迭代都获取一个新句柄。
关于javascript - 使用 JavaScript 在 HTML 中一次放置多个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14726529/