4

編集: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);
};

<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 をチェックすると、次のようになります。

エラー: 画像が破損しているか、切り捨てられています

4

3 に答える 3

3

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また、反復ごとに新しいハンドルを取得するのではなく、のハンドルを取得して変数に格納するという小さな改善も追加しました。

于 2013-02-06T10:33:43.127 に答える
0

これを試して:

var placeImage = function(x) {
var img="";
for (var counter = 1; counter <= x; counter++ ) {
     img += '<img src="borboleta\Borboleta'+counter+'.png" alt="" />';
}
    document.getElementById("div_picture_right").innerHTML = img;
};

placeImage(48);

このコードでは、48ではなく1つのDOM操作しかありません。また、上記のID(div_picture_right)を持つ要素があるかどうかを確認してください。

于 2013-02-06T10:21:43.763 に答える
0

div の z-index を動的に変更する場合は、位置属性を「相対」ではなく「絶対」に設定します。その方が理にかなっています。

于 2013-02-08T10:35:40.913 に答える