2012-10-06 21 views
2

可能重複:
jQuery check if image is loadedjQuery的替代跨度與IMG的時間併爲您IMG的加載

我有一個情況我有以下標記:

<div class="image"> 
    <img class="" src="content-images/1.jpg"> 
    <span class="slide" rel="content-images/2.jpg"></span> 
    <span class="slide" rel="content-images/3.jpg"></span> 
    <span class="slide" rel="content-images/4.jpg"></span> 
</div> 

現在在CSS中,所有div.image的孩子都被絕對定位,所以他們被堆放在t彼此運作。

我正在做的事情是,在一定的觸發,讓被點擊一個按鈕,其他地方在頁面上,給span年代到img「與src集到rel在每個跨度變化看說。這些圖像是大型高分辨率圖像,因此可能需要一段時間才能完全加載。

使用javascript/jQuery我需要顯示一個加載消息/指標,從按鈕被點擊時,所有的span被替換爲img的完成加載。

我不能使用jQuery因爲與圖像和緩存等

我嘗試使用imagesloaded,但它似乎並沒有做什麼,我需要的已知問題的​​。

有沒有其他方法可以做到這一點,你可以想到的?

+0

可以形象的'height'和'width'在裝載之前它一直保持0。不要knw,如果它的跨瀏覽器 – Jashwant

+0

[預加載圖片在頁面加載?](http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/) – ocanal

+0

@ocanal:那是什麼我正在努力。你具體是什麼意思? –

回答

0

我不太清楚,如果這就是你想達到什麼,但你可以試試看......

$("#button").click(function(){ 
    console.log("Started loading..."); 
    // Get all spans to replace, and count them 
    var imgSpans = $("div.image span.slide"), 
     toLoad = imgSpans.length, 
     loaded = 0; 
    // Now load each image 
    for (var i = 0; i < toLoad; ++i) { 
     // Closure to keep correct value of i 
     (function(i){ 
      // Preload image 
      var img = new Image(); 
      img.src = imgSpans.eq(i).attr("rel"); 
      img.onload = function(){ 
       // When loading has finished, replace span with img... 
       imgSpans.eq(i).replaceWith(img); 
       if (++loaded == toLoad) { 
        // ...and check if all images have been loaded by now 
        console.log("Finished loading..."); 
       } 
      }; 
     })(i); 
    } 
}); 

DEMO (JSFiddle)