2013-01-08 32 views
0

可能重复:
JavaScript Preloading ImagesHTML隐藏图像 - 如何下载和大小之前揭示?

我使用JS设置img.hidden =假一段时间的页面加载后。这会导致图像下载并调整img元素的大小 - 我想避免这种情况(我使用内联样式宽度:2em来调整图像大小)。其次,当我更改img源代码时,第二张图片下载会有一点点延迟。

如何在显示页面之前下载图像...?

+0

'display:none' on the css? –

+0

看到这里http://stackoverflow.com/questions/3646036/javascript-preloading-images – Loris

回答

2

首先下载图像,然后触发动作,以这种方式使用jQuery:

var i = document.createElement('img'); // or new Image() 
    // may be you need to set the element id... 
    i.id = 'your id'; 
    // here handle on load event 
    $(i).load(function() { 

     // finally the new image is loaded, you can trigger your action 
     $('#container').append($(this)); 

    }); 
    // This is the last step, set the url and start the image download. 
    i.src = 'http://www.hostname.com/yourimage.jpg'; 
1

没有的jQuery(如果需要):

var imageNode = new Image(); // or document.createElement('img'); 

imageNode.onload = function(e) { 
    // Code for appending to the DOM 
    document.getElementById('container').appendChild(this); 
}; 

imageNode.src = 'path/to/image.jpg'; 

如果你的img标签确实已经像这样存在:

<img id='myimg' alt=''> 

在JavaScript中使用:

var imageNode = document.getElementById('myimg'); 

相反的:

var imageNode = new Image(); 

请记住,代码需要img标签后执行或当DOM就绪/加载。否则当代码执行时不存在

+0

我只是想知道如何做到这一点没有jQuery :) – freedev

+0

我如何将这与我的html中的标签? – icekreaman

+0

好的,我已经编辑了一些关于如何将这与现有的img标签一起使用的更多说明。请检查它是否有帮助。 – freakerd

相关问题