静态图片的图像加载事件(Image onload)

8

我知道为了让图片的onload起作用,你必须在加载处理程序后设置src。但是我想将onload处理程序附加到我的HTML中静态的图像。目前,我是这样做的(使用jQuery):

<img id='img1' src='picture.jpg'>

$('#img1').load( function() {
 alert('foo');
})
.attr('src', $('img1').attr('src'));

但是这种方法比较丑陋,而且它的缺陷很明显,只能用于匹配单个图像的选择器。有没有其他更好的方法可以做到这一点呢?

编辑
我所说的只能对匹配单个图像的选择器进行操作是指在执行以下操作时:

<img class='img1' src='picture.jpg'>
<img class='img1' src='picture2.jpg'>

$('.img1').load( function() {
 alert('foo');
})
.attr('src', $('.img1').attr('src'));

两张图片的src都将为'picture.jpg'

4个回答

10

你可以通过调用 .trigger().load() 直接触发事件或它的处理程序。

如果你知道你想要的事件,因为你知道图像已经加载完成了,那么你可以这样做:

$('#img1').load(function() {
    alert('foo');
  })
  .trigger('load');  // fires the load event on the image

如果你的脚本在文档准备好或一些还不确定图片是否存在的时候运行,那么我建议使用类似下面这样的代码:

$('img.static')
  .load(function(){
    alert('foo');
    return false; // cancel event bubble
  })
  .each(function(){
    // trigger events for images that have loaded,
    // other images will trigger the event once they load
    if ( this.complete && this.naturalWidth !== 0 ) {
      $( this ).trigger('load');
    }
  });

请注意,load事件会冒泡(自jQuery 1.3起),如果您没有在img处理程序中取消冒泡,则可能会过早地触发文档上的load处理程序。

记录一下:对于Safari浏览器,使用img.src=img.src触发解决方案将不起作用。您需要将src设置为其他内容(例如#或about:blank),然后再改回来以实现重新加载。


3

好的,我将Borgars的答案转换成了一个插件,这是它:

$.fn.imageLoad = function(fn){
    this.load(fn);
    this.each( function() {
        if ( this.complete && this.naturalWidth !== 0 ) {
            $(this).trigger('load');
        }
    });
}

你应该在结尾处返回this,以允许链接 :) - Vjeux

0
在您想要此功能的图像中添加一个类,并在jQuery选择器中使用该类。
$('.static-image').load( function(){ ... } );

0

我想这实际上是一个关于jQuery选择器的问题。如果你想匹配所有的图像元素,那么你可以使用img而不是#img1作为你的选择器。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接