Image onload for static images

后端 未结 4 1511
轮回少年
轮回少年 2021-01-02 12:05

I know that for the image onload to work you have to set the src after the onload handler was attached. However I want to attach onload handlers to images that are static in

相关标签:
4条回答
  • 2021-01-02 12:38

    Add a class to images where you want this functionality and use that class in the jQuery selector.

    $('.static-image').load( function(){ ... } );
    
    0 讨论(0)
  • 2021-01-02 12:40

    I guess this is really a question about jQuery selectors. If you would like to match all your image elements then you can use img instead of #img1 as your selector.

    0 讨论(0)
  • 2021-01-02 12:41

    You can trigger the event (or it's handler) directly by calling .trigger() or .load().

    If you know that you want the event, because you know that the images are already loaded, then you can do it like this:

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

    If you are running your script on document ready or some moment where it isn't yet clear if the images are there or not, then I would use something like this:

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

    Be warned that the load event bubbles (jQuery 1.3) and you might possibly be triggering a load handler on the document prematurely if you don't cancel the bubble in the img handler.

    For the record: The img.src=img.src triggering solution will unfortunately not work correctly on Safari. You will need to set the src to something else (like # or about:blank) and then back for reload to happen.

    0 讨论(0)
  • 2021-01-02 12:51

    Okay, I turned Borgars answer into a plugin, here it is:

    $.fn.imageLoad = function(fn){
        this.load(fn);
        this.each( function() {
            if ( this.complete && this.naturalWidth !== 0 ) {
                $(this).trigger('load');
            }
        });
    }
    
    0 讨论(0)
提交回复
热议问题