javascript - 使用 JavaScript 在 HTML 中一次放置多个图像

标签 javascript html image

编辑:这是另一个问题:我无法用 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/

相关文章:

java - java中的文本转图像

android - 如何让移动网页在所有设备上显示相同

javascript - Internet Explorer 11 中的 SCRIPT438 错误

javascript - 原型(prototype) - 带有 id 的元素中带有 styleclass 的元素?

javascript - 在 Express 应用程序中动态填充模态

php - 启用所有选择选项直到 selectedIndex

html - 同一张图片使用了三次,但通过 CSS 只出现了两次

javascript - 使用 javascript 操作日期对象

javascript - 在 string.split 中查找标记的复杂 jquery 选择器

CSS - 在其他 div 周围 float 子 div