背景图像加载时触发事件

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

你可以这样做,

演示

$('').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(); }); 
 $('').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的问题是缓存: 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.... }); 
 $(document).ready(function(){ $('img, .hasBGI').css('opacity',0) $('.hasBGI').each(function(){ var $this = $(this) $bgi = $('') // $bgi.css(/*hiddingStyle*/) $('body').append($bgi) $bgi.load(function(){ $(this).remove() $this.animate({opacity:1}) }) }) $('img').load(function(){ $(this).animate({opacity:1}) }) 

})