代码之家  ›  专栏  ›  技术社区  ›  Pim Jager

静态图像的图像加载

  •  8
  • Pim Jager  · 技术社区  · 17 年前

    我知道,要使映像onload工作,您必须在onload处理程序被附加后设置src。但是,我想将onload处理程序附加到HTML中静态的图像上。现在,我通过以下方式(使用jQquery)实现这一点:

    <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'));
    

    4 回复  |  直到 17 年前
        1
  •  10
  •   Borgar    15 年前

    您可以通过调用 .trigger() .load() .

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

    如果您在document ready(文档准备就绪)上运行脚本,或者在某个时刻还不清楚图像是否存在,那么我会使用以下内容:

    $('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');
        }
      });
    

    记录在案的是: img.src=img.src src 然后返回以进行重新加载。

        2
  •  3
  •   Borgar    15 年前

    好的,我把Borgars的答案变成了一个插件,它是:

    $.fn.imageLoad = function(fn){
        this.load(fn);
        this.each( function() {
            if ( this.complete && this.naturalWidth !== 0 ) {
                $(this).trigger('load');
            }
        });
    }
    
        3
  •  0
  •   Ken Browning    17 年前

    我想这确实是一个关于jQuery选择器的问题。如果要匹配所有图像元素,则可以使用 img 而不是 #img1

        4
  •  0
  •   james    17 年前

    $('.static-image').load( function(){ ... } );