2010-07-19 121 views
12

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

+0

的可能的复制[我如何检查是否背景图像加载?](http://stackoverflow.com/questions/5057990/how-can-i-check-if-a-background-image-is-loaded) – azerafati 2016-10-02 12:39:18

回答

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

这会等到图像加载或直到有价值的回报'background-image'属性? – Squirkle 2010-07-19 14:04:38

+1

实际上发生了什么,它是否会等待图像加载...在这种情况下,身体标记的背景图像... – Reigel 2010-07-19 14:37:48

+0

这是一个非常巧妙的技巧。它是如何工作的?我无法弄清楚$('')的目标是什么...... – Squirkle 2010-07-19 15:21:46

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中仍然失败。任何人有一个即修复?

+2

我已经修复根据您的代码和意见接受的答案 – 2012-03-09 19:33:11

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

})

+0

我的意图是图像平滑下载 – domSurgeon 2013-07-05 15:01:33