背景图像加载时触发事件

Squ*_*kle 13 jquery

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

Rei*_*gel 22

你可以这样做,

演示

$('<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();
});
Run Code Online (Sandbox Code Playgroud)

  • 该演示基于Fresheyeball的笔记我已修复它:http://jsfiddle.net/7bmhf/ (2认同)