静态图像的图像加载完成。

29 浏览
0 Comments

静态图像的图像加载完成。

我知道为了使图像的 onload 生效,必须在 onload 处理程序附加后设置 src。然而,我想在我的 HTML 中为静态图片附加 onload 处理程序。目前我是这样做的(使用 jQuery):\n


\n

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

\n但这样做相当丑陋,并且明显有一个问题,即它只能应用于仅匹配一个图像的选择器。是否有其他更好的方法来做到这一点?\n编辑:\n我所指的只能应用于仅匹配一个图像的选择器是指当进行以下操作时:\n



\n

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

\n这两个图片都将具有 src=\'picture.jpg\'。

0
0 Comments

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

Here is an example of how you can use the img selector to apply the onload event to all image elements:

以下是一个如何使用img选择器将onload事件应用于所有图像元素的示例:

$(document).ready(function(){
  $('img').on('load', function(){
    // Do something when the image is loaded
  });
});

This code will apply the onload event to all img elements on the page. When an image is loaded, the code inside the event handler will be executed.

这段代码将在页面上的所有img元素上应用onload事件。当图像加载完成时,事件处理程序内的代码将被执行。

Using the img selector instead of #img1 allows you to apply the onload event to all image elements, not just the one with the ID "img1".

使用img选择器而不是#img1允许您将onload事件应用于所有图像元素,而不仅仅是具有ID“img1”的图像元素。

This can be useful if you have multiple image elements on the page and you want to perform the same action when any of them are loaded.

如果页面上有多个图像元素,并且您希望在它们中的任何一个加载时执行相同的操作,那么这将非常有用。

In summary, the issue with the original code is that it is only applying the onload event to a specific image element with the ID "img1". Using the img selector instead allows you to apply the event to all image elements on the page.

0
0 Comments

问题出现的原因:当使用Image.onload事件来加载静态图片时,有可能会出现图片加载不完整或加载失败的情况。

解决方法:使用上述代码中的插件,通过判断图片的complete属性和naturalWidth属性,来手动触发load事件,以确保图片加载完成。

以下是代码整理的文章:

当使用Image.onload事件来加载静态图片时,有可能会出现图片加载不完整或加载失败的情况。为了解决这个问题,我将Borgars的答案转换成了一个插件,如下所示:

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

在这段代码中,我们首先使用load()方法来绑定传入的回调函数。然后,通过遍历每个图片元素,判断其complete属性和naturalWidth属性。如果图片已经加载完成且其自然宽度不为0,我们手动触发load事件。最后,为了支持链式调用,我们需要在代码末尾返回this。

使用这个插件,我们可以确保静态图片的完整加载。

0
0 Comments

当我们需要对静态图片进行加载事件处理时,可能会遇到以下问题:图片加载事件无法触发,导致无法执行相应的处理逻辑。为了解决这个问题,可以采取以下方法:

1. 如果我们确定图片已经加载完成,并且想要手动触发加载事件,可以使用.trigger().load()方法。示例如下:

$('#img1').load(function() {
    alert('foo');
  })
  .trigger('load');  // 触发图片的加载事件

2. 如果脚本在文档准备就绪或者其他一些不确定图片是否已经加载完成的时刻执行,可以使用以下方法来处理:

$('img.static')
  .load(function(){
    alert('foo');
    return false; // 取消事件冒泡
  })
  .each(function(){
    // 对已加载完成的图片触发事件,
    // 其他图片在加载完成后会触发事件
    if ( this.complete && this.naturalWidth !== 0 ) {
      $( this ).trigger('load');
    }
  });

需要注意的是,load事件会冒泡(jQuery 1.3版本起),如果不取消图片的事件冒泡,可能会在图片处理程序执行之前就触发文档的加载事件。

需要说明的是,img.src=img.src的触发加载解决方案在Safari上无法正常工作,需要将src设置为其他值(如#或about:blank),然后再重新设置回来才能实现重新加载的效果。

0