2013-08-31 98 views
0

我有這樣的功能,應該等待直到加載背景圖像,然後將圖像的比例添加到它的容器並淡入背景圖像容器中。它似乎在Chrome中工作,但在Internet Explorer中失敗8和9,並不總是在10中工作。在ie8似乎不瞭解jquery('load')事件。在ie 9和10中,它並不總是找到背景圖像的寬度。我如何使它在ie8 +和其他主流瀏覽器中工作?JS/jQuery:加載背景圖片

JS:

$('.item').each(function(index) { 
    var thisItem = $(this); 
    var image_url = thisItem.find('.img').css('background-image'); 
    var img = new Image(); 
    img.src = image_url.replace(/(^url\()|(\)$|[\"\'])/ig, ''); 
    if (image_url){ 
    //initialize only when background img is loaded 
    var $img = $('<img>').attr('src', img.src).on('load', function(){ 
     //don't allow img to be larger than it is 
     if(img.width < thisItem.width()){thisItem.css({'max-width':img.width+'px'});} 
     var ratio = img.height/img.width; 
      thisItem.find('.item_ratio').css({'padding-bottom':ratio*100+'%'}); 
      thisItem.find('.img').fadeIn(800); 

     }); 
    } 
}); 

HTML:

<div class="item"> 
    <div class="img" style="background-image:url('some_url'); width: 100%; background-size: cover;"></div> 
    <div class="item_ratio"></div> 

    <!-- Some other not important html -> 

</div> 

回答

0

影像上load事件已被證明是不可靠/不存在,這就是爲什麼有a well-known jQuery plugin幫助理順事情了跨瀏覽器。我建議看看,而不是試圖找出瀏覽器問題和邊緣情況下,如瀏覽器從緩存中獲取圖像時缺少加載事件等。

編輯:代碼示例使其與懸掛工作<img/> (未經測試)

//initialize only when background img is loaded 
var $img = $('<img>').attr('src', img.src).prependTo(thisItem).hide().imagesLoaded(function() { 
    //don't allow img to be larger than it is 
    //... [your code] 
}); 

我用這種方法here。 (左側的大拇指是單個背景圖像精靈,一旦圖像載入,我就會對這些精靈進行動畫處理)。

另外,您也可以在CSS中使用background-size: contain。這樣做可能會在更新的瀏覽器(如果圖像很大)中更高性能,並且因爲您不需要任何代碼而更加簡單。它在IE8中不受支持,如果您使用的是Modernizr,您可以測試它。這可能是我的首選方法,但我通常包括Modernizr。因人而異。

+1

實際上,該插件不支持我真正需要的背景圖像 – vlad

+0

我看到您正在監聽'$('')'上的'load'事件。但是,您可能需要實際將其插入到DOM中(隱藏)以使'load'觸發。我最近做了這件事,它的工作可靠。 –