2009-07-29 43 views
1

之間對於很多的小縮略圖的網站,我想用一個佔位符,GIF,而每個圖像加載。這需要像下面的代碼:平鋪一個異步加載圖像 - 把一個<img>和背景URL

$('.this_img').each(function(){ 
    var $this_img = $(this); 
    var $this_src = $(this).find('.sliderImage:first').attr('src'); 
    var img = new Image(); 
    // wrap our new image in jQuery, then: 
    $(img) 
    // set minimum dimensions 
    .css({ 
    'min-height': '35px', 
    'min-width': '40px' 
    }) 
    // once the image has loaded, execute this code 
    .load(function() { 
    // set the image hidden by default  
    $(this).hide(); 

    // with the holding div #loader, apply: 
    $this_img 
     // remove the loading class (so no background spinner), 
     .removeClass('loading') 
     // then insert our image 
     .prepend(this); 

    // fade our image in to create a nice effect 
    $(this).fadeIn(); 
    }) 

    // if there was an error loading the image, react accordingly 
    .error(function() { 
    // notify the user that the image could not be loaded 
    }) 

    // *finally*, set the src attribute of the new image to our image 
    .attr('src', $this_src); 

這種運作良好,在樣式表中指定的佔位符,但我希望能夠平鋪這些圖像,如果他們太短或狹窄,背景CSS是顯而易見的方式做到這一點,但它無法與異步圖像加載兼容的,據我所知。

我的問題:有沒有可用於平鋪<img>標記的jQuery(或CSS3)?

或者,有沒有辦法做一個形象的臺異步加載,然後將其粘貼到後臺的CSS屬性?這聽起來有點太神奇了,但也許它有用。

回答

1

你可以發佈你的HTML標記結構?在盲目,否則,但你嘗試modifyu包含div的background屬性?

// your callback function 

function() { 
    // set the image hidden by default  
    $(this).hide(); 

    // with the holding div #loader, apply: 
    $this_img 
     // remove the loading class (so no background spinner), 
     .removeClass('loading') 
     // then insert our image 
    //.prepend(this) 

.css('background','transparent url(「'+ $ this_src +'」)top left repeat');

// fade our image in to create a nice effect 
    $(this).fadeIn(); 
    } 
+0

這是一個很好的答案,但目標是等到圖像完成下載後,我發佈的JS代碼纔會這樣做。據我所知,沒有辦法與背景圖像屬性來做到這一點。 – jamtoday 2009-07-30 03:00:44