我有這樣的功能,應該等待直到加載背景圖像,然後將圖像的比例添加到它的容器並淡入背景圖像容器中。它似乎在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>
實際上,該插件不支持我真正需要的背景圖像 – vlad
我看到您正在監聽'$('')'上的'load'事件。但是,您可能需要實際將其插入到DOM中(隱藏)以使'load'觸發。我最近做了這件事,它的工作可靠。 –