背景图像加载时触发事件

时间:2010-07-19 13:52:39

标签: jquery

有没有办法,使用jQuery,在加载CSS背景图片时触发事件?

4 个答案:

答案 0 :(得分:22)

你可以这样做,

demo

$('<img>').load(function(){
    // make sure to bind the load event BEFORE setting the "src"
    alert('image loaded');
}).attr('src',function(){
    var imgUrl = $('body').css('background-image');
    imgUrl = imgUrl .substring(4, imgUrl .length-1);
    return imgUrl;
}).each(function() {
    // fail-safe for cached images which sometimes don't trigger "load" events
    if(this.complete) $(this).load();
});

答案 1 :(得分:2)

$('<img>').attr('src',function(){
    var imgUrl = $('#body').css('background-image');
    imgUrl = imgUrl .substring(5, imgUrl .length-2);
    return imgUrl;
}).load(function(){
    //Do Something
});

不禁注意到上面的代码在小提琴中不起作用。看起来像是因为它返回“url('/ img-path.jpg')”而不仅仅是“/img-path.jpg”。

但是这种方法在IE中仍然失败。任何人都有一个ie fix?

答案 2 :(得分:2)

我发现IE的问题是缓存:http://www.witheringtree.com/2009/05/image-load-event-binding-with-ie-using-jquery/

所以你可以试试这个:

$(”).attr({src: src + ‘?random=’ + (new Date()).getTime()}).load(function (){
  //custom code here....
});

答案 3 :(得分:0)

$(document).ready(function(){
$('img, .hasBGI').css('opacity',0)

$('.hasBGI').each(function(){
    var $this = $(this)
        $bgi = $('<img src="'+/*folderFix*/$this.css('backgroundImage')+'">')
        // $bgi.css(/*hiddingStyle*/)
        $('body').append($bgi)
        $bgi.load(function(){
            $(this).remove()
            $this.animate({opacity:1})
        })
})
$('img').load(function(){
    $(this).animate({opacity:1})
})

})