我有这样的功能,应该等待直到加载背景图像,然后将图像的比例添加到它的容器并淡入背景图像容器中。它似乎在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'触发。我最近做了这件事,它的工作可靠。 –