Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/409.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript JS/jQuery:背景图像加载_Javascript_Jquery_Background Image_Onload - Fatal编程技术网

Javascript JS/jQuery:背景图像加载

Javascript JS/jQuery:背景图像加载,javascript,jquery,background-image,onload,Javascript,Jquery,Background Image,Onload,我有一个函数,它应该等到背景图像被加载,然后将图像的比率添加到它的容器中,然后淡入背景图像容器。它似乎可以在Chrome中使用,但在InternetExplorer8和9中失败,并且在10中并不总是有效。在ie8中,它似乎不理解jquery on('load')事件。在IE9和IE10中,它并不总能找到背景图像的宽度。如何使其在ie8+和其他主流浏览器中工作 js: $('.item')。每个(函数(索引){ var thisItem=$(此项); var image_url=thisItem.

我有一个函数,它应该等到背景图像被加载,然后将图像的比率添加到它的容器中,然后淡入背景图像容器。它似乎可以在Chrome中使用,但在InternetExplorer8和9中失败,并且在10中并不总是有效。在ie8中,它似乎不理解jquery on('load')事件。在IE9和IE10中,它并不总能找到背景图像的宽度。如何使其在ie8+和其他主流浏览器中工作

js:

$('.item')。每个(函数(索引){
var thisItem=$(此项);
var image_url=thisItem.find('.img').css('background-image');
var img=新图像();
img.src=image\u url.replace(/(^url\()\(\)$\[\“\”])/ig',);
如果(图像地址){
//仅在加载后台img时初始化
变量$img=$('
html:



图像上的
load
事件被证明是不可靠的/不存在的,这就是为什么有必要帮助解决跨浏览器的问题。我建议您看看这一点,而不是试图找出浏览器问题和边缘情况,例如浏览器从缓存中获取图像时丢失加载事件等

编辑:编写示例代码,使其与悬挂的

我使用了这种方法(左边的拇指是一个单一的背景图像精灵,一旦图像加载,我就会在其中设置动画)


另外,您还可以在CSS中使用。在较新的浏览器中(如果图像较大),这样做可能会更有效而且更简单,因为你不需要任何代码。IE8不支持它,如果你使用Modernizer,你可以测试它。这可能是我的首选方法,但我通常包括Modernizer.YMMV。

实际上,该插件不支持我真正需要的背景图像。我看到你正在收听
加载nt在
$(“”)
上。但是,您可能需要实际将其插入DOM(隐藏),才能启动
加载
。我最近做了这件事,它工作可靠。
$('.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);

        });
    }
});
<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>
//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]
});