How can i clone an image in javascript

允我心安 提交于 2019-12-03 11:07:57

Afaik the default browser behavior is to cache images. So something like this should work the way you want:

 var sourceImage = document.createElement('img'),
     imgContainer = document.getElementById("content");
 sourceImage.src = "[some img url]";
 imgContainer.appendChild(sourceImage);

 function cloneImg(){
     imgContainer.appendChild(sourceImage.cloneNode(true));
 }

It's all pretty sop, so it should run in IE6 too (I don't have it, so can't test that). See it in action

Furthermore, you may want to check the cache setting of your IE6 browser. I remember from the not so good old days with IE<8 that I sometimes reverted to setting the cache to refresh "every time you load the page" (or someting like that).

javascript has provisions for this build in. here is code modified from Danny Goodman's Javascript Bible 2nd Ed p.498,500 for cacheing/preloading an image,

<img src='/images/someotherimage1.png' id='img1'>
<img src='/images/someotherimage2.png' id='img2'>
<img src='/images/someotherimage3.png' id='img3'>
<script type="text/javascript">
function assignall(numImages, x, y) {
    var img = new Image(x, y);
    img.src = '/images/someimage.png';
    var x;
    for (x=1; x <= numImages; x++) {
        document.getElementById('img'+x).src = img.src;
    }
}

assignall(3); //do it.
</script>

you can always use an array if you have a number of images to work with.

var img = new Array();
function initallimages(numImages, x, y) {
    var x;
    for (x=1; x <= numImages; x++) {
        img['img' + x] = new Image(x,y);
        img['img' + x].src = '/images/someimage.png';
    }
 }
 function assignallimages(numImages) {
    var x;
    for (x=1; x <= numImages; x++) {
        document.getElementById('img' + x).src = img['img'+x]['img' + x].src;
    }
}

initallimages(3, 320, 240);
assignallimages(3);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!