JS / jQuery:背景图像onload

时间:2013-08-31 14:36:42

标签: javascript jquery background-image onload

我的功能应该等到加载背景图像然后将图像的比例添加到它的容器并淡入背景图像容器中。它似乎在Chrome中工作,但在Internet Explorer 8和9中失败,并不总是在ie8中它似乎不理解jquery on('load')事件。在ie 9和10中,它并不总是找到背景图像的宽度。如何在ie8 +和其他主流浏览器中使用它?

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>

1 个答案:

答案 0 :(得分: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。 YMMV。