Get the real width and height of an image with JavaScript? (in Safari/Chrome)

后端 未结 30 2719
傲寒
傲寒 2020-11-22 01:16

I am creating a jQuery plugin.

How do I get the real image width and height with Javascript in Safari?

The following works with Firefox 3, IE7 and Opera 9:

30条回答
  •  孤城傲影
    2020-11-22 01:33

    As stated before, Xavi answer won't work if images are in the cache. The issue responds to webkit not firing the load event on cached images, so if the width/height attrs are no explicitly set in the img tag, the only reliable way to get the images is to wait for the window.load event to be fired.

    The window.load event will fire always, so it's safe to access the width/height of and img after that without any trick.

    $(window).load(function(){
    
       //these all work
    
       $('img#someId').css('width');
       $('img#someId').width();
       $('img#someId').get(0).style.width;
       $('img#someId').get(0).width; 
    
    });
    

    If you need to get the size of dynamically loaded images that might get cached (previously loaded), you can use Xavi method plus a query string to trigger a cache refresh. The downside is that it will cause another request to the server, for an img that is already cached and should be already available. Stupid Webkit.

    var pic_real_width   = 0,
        img_src_no_cache = $('img#someId').attr('src') + '?cache=' + Date.now();
    
    $('').attr('src', img_src_no_cache).load(function(){
    
       pic_real_width = this.width;
    
    });
    

    ps: if you have a QueryString in the img.src already, you will have to parse it and add the extra param to clear the cache.

提交回复
热议问题