2012-06-12 31 views
1

爲什麼加載的內容,但圖像仍在加載? 如何加載內容(包含內容的圖片)然後淡入?如何加載內容(包含內容的圖片)然後淡入?

JS

$(document).ready(function(){ 
    $('#contents').fadeOut('slow', function(){ 
     $(this).load("url", {}, function(){ 

      $("#contents").fadeIn('slow', function(){ 

       alert('Faded in!'); 

      }); 

     }); 

    }); 
}); 

回答

3

事實並非如此簡單。您需要將加載處理程序加載到動態加載的圖像上,但不修改源代碼HTML,直到它們已經開始加載纔會這樣做,這使得它更復雜一些,因爲在檢查之前可能會完成一些操作。所以,你可以做這樣的事情,它獲取動態加載的內容中的所有圖像對象,然後檢查每個圖像對象是否已完成加載。如果它尚未完成加載,則會安裝一個onload處理程序,以便在最後一次加載完成時進行計數。當所有人都加載完畢,我們就可以做fadeIn()

$(document).ready(function(){ 
    $('#contents').fadeOut('slow', function(){ 
     var self = $(this); 

     function fadeIn() { 
      $("#contents").fadeIn('slow', function(){ 
       alert('Faded in!'); 
      }); 
     } 

     self.load("url", {}, function() { 
      var imgs = self.find("img"); 
      var imgsRemaining = imgs.length; 
      imgs.each(function() { 
       // if the image isn't already loaded, then attach an onload handler 
       if (!img.complete || !this.height || !this.width) { 
        this.onload = this.onerror = this.onabort = function() { 
         // decrement imgsRemaining 
         --imgsRemaining; 
         // if no more images to finish loading, then start the fade 
         if (imgsRemaining == 0) { 
          fadeIn(); 
         } 
        }); 
       } else { 
        // this image already loaded 
        --imgsRemaining; 
       } 
      }); 
      // if there were no images that weren't loaded yet 
      if (imgsRemaining == 0) { 
       fadeIn(); 
      } 
     }); 
    }); 
}); 

或者,解決問題的一點點更通用的方式,下面是加載內容的通用jQuery的方法,然後調用回調當內容和內容中的所有圖像都完成加載時。這將更加可重用,並可能使您的代碼更具可讀性。您可以使用它就像.load(url, data, fn) method

jQuery.fn.loadComplete = function(url, data, fn) { 
    // check if optional data argument is missing 
    if (typeof data == "function") { 
     fn = data; 
     data = {}; 
    } 
    // dynamically load the content 
    this.load(url, data, function() { 
     var self = this; 
     // when content is parsed, check to see when all images are loaded 
     var imgs = $(this).find("img"); 
     var imgsRemaining = imgs.length; 
     imgs.each(function() { 
      if (this.complete) { 
       // if image is already loaded, just decrement the count 
       --imgsRemaining; 
      } else { 
       // image not loaded yet, install onload handler 
       this.onload = this.onerror = this.onabort = function() { 
        // when img has finished loading, check to see if all images are now loaded 
        if (--imgsRemaining == 0) { 
         fn.call(self); 
        } 
       }; 
      } 
     }); 
     if (imgsRemaining == 0) { 
      fn.call(self); 
     } 
    }); 
} 

所以,用這種新方法,您的代碼將僅僅是這樣的:

$(document).ready(function(){ 
    $('#contents').fadeOut('slow', function(){ 
     $(this).loadComplete("url", {}, function(){ 
      $("#contents").fadeIn('slow', function(){ 
       alert('Faded in!'); 
      }); 
     }); 
    }); 
}); 
+0

那偉大的!非常詳細。我用了第二個,非常感謝! – user964351