Image does not have width at document.ready

后端 未结 3 1866
孤独总比滥情好
孤独总比滥情好 2020-12-21 15:02

I have a function that I wish to use to resize images:

http://jsfiddle.net/eUurB/

When I run it on document.ready, it has no effect; the image size returned

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-21 15:26

    Here's an ultra-safe way to do it that doesn't require waiting for all the images to load, and takes care of situations where the image may be cached or finished loading before the DOM is ready.

    $('#my_img').one('load',function(){
        resizeImgByArea('logo', 50);
    })
      .filter(function(){
         return this.complete;
    })
      .load();
    

    • .one('load',...) removes the handler as soon as it is invoked. You only need it once.

    • .filter() will return the image if it was already loaded. If not, it returns no elements.

    • .load() will manually invoke the handler. This will only occur if the image was already loaded.


    So if the image was preloaded before the DOM was ready, we'll invoke its .load() handler manually. If not, its handler will be invoked when it is loaded.

提交回复
热议问题