开发者

Replace images in a DIV using JavaScript

I want开发者_如何学Python to show different images in a DIV, the turn of an image depend on a random number. The image name is like 1.gif, 2.gif, .. 6.gif

to do that I coded

var img = document.createElement("IMG");
img.src = "images/1.gif";
document.getElementById('imgDiv').appendChild(img);

but it does not replace the old image how ever it add an another image right in the bottom of first image.

syntax for DIV is:

<div id="imgDiv" style="width:85px; height:100px; margin:0px 10px 10px 375px;"></div>

may u halp me ?


var img = document.createElement("IMG");
img.src = "images/1.gif";
var oldImg = document.getElementById('oldImg');
document.getElementById('imgDiv').replaceChild(img, oldImg);


var dv = document.getElementById('imgDiv');

// remove all child nodes
while (dv.hasChildNodes()) { 
    dv.removeChild(dv.lastChild); 
} 

var img = document.createElement("IMG"); 
img.src = "images/hangman_0.gif"; 
dv.appendChild(img); 


If you want to replace an element, you need to use replaceChild, not appendChild.


I would not recommend changing the src of the element in question. That would cause a lag in the display of the next image while the browser downloads the next image. If you have a set number of images you would want to preload them the way you are doing so now.

If you have the following code:

 <div id="imgDiv" style="width:85px; height:100px; margin:0px 10px 10px 375px;"></div>

You can do this:

<script type="text/javascript>
     var nextImage = document.createElement("img");
     nextImage.src = "your source here";

     document.getElementById("imgDiv").appendChild(nextImage);
</script>

Now that you have an image in place you can use the replaceChild() method:

var imageDiv = document.getElementById("imgDiv");
imageDiv.replaceChild(nextImage, imageDiv.childNodes[0]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜