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

后端 未结 30 2383
傲寒
傲寒 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:48

    The root problem is that WebKit browsers (Safari and Chrome) load JavaScript and CSS information in parallel. Thus, JavaScript may execute before the styling effects of CSS have been computed, returning the wrong answer. In jQuery, I've found that the solution is to wait until document.readyState == 'complete', .e.g.,

    jQuery(document).ready(function(){
      if (jQuery.browser.safari && document.readyState != "complete"){
        //console.info('ready...');
        setTimeout( arguments.callee, 100 );
        return;
      } 
      ... (rest of function) 
    

    As far as width and height goes... depending on what you are doing you may want offsetWidth and offsetHeight, which include things like borders and padding.

提交回复
热议问题