使用 JavaScript 同时将多个图像放入 HTML 中

use*_*416 5 html javascript image

编辑:这是另一个问题:我无法Z-index使用 for 循环定义每张图片。

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);
};
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

在检查 FireBug 时,我得到以下信息:

错误:图像损坏或被截断

MrC*_*ode 4

看起来您的代码是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);
};
Run Code Online (Sandbox Code Playgroud)

我还添加了一个小改进,即获取句柄并将其div存储在变量中一次,而不是在每次迭代时获取新句柄。