开发者

Trigger event on background image load

Is there a way, using jQuer开发者_Python百科y, to trigger an event on load of a CSS background image?


you could do it like this,

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();
});


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

Could not help but notice that the above code does not work in fiddle. Looks like its because it returns "url('/img-path.jpg')" instead of just "/img-path.jpg".

However this method still fails in IE. Anyone have an ie fix?


I found that the problem with IE is cache: http://www.witheringtree.com/2009/05/image-load-event-binding-with-ie-using-jquery/

so you could try this:

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


$(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})
})

})

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜