2013-01-08 27 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

相關問題