can't get true height/width of object in chrom

2019-03-15 20:51发布

问题:

I have a question, if i set a image height in css and try to get height/width i get different results in different browsers. Is there a way to get the same dimension in all browsers?

You can find a live example here<-Removed

and the concept is like this:

CSS:
img{
  height:100px;
  }

Script:
$(document).ready(function(){
    $("#text").append($("#img_0").attr("height"));
    $("#text").append($("#img_0").attr("width"));
});

Output Firefox: img height: 100 img width: 150

Output Chrome: img height: 100 img width: 0

Output Chrome: img height: 100 img width: 93?

i have tried this from StackOverflow: stackoverflow.com/questions/1873419/jquery-get-height-width

but still get the same result

Any one know a good solution?

回答1:

The images aren't loaded in document.ready, you need to use the window.load event to make sure they're present, like this:

$(window).load(function(){
    $("#text").append($("#img_0").height());
    $("#text").append($("#img_0").width());
});

Here's a quick read on the difference, the important part is that pictures are loaded.



回答2:

Nick Craver's answer to use $(window).load() is correct, but the images also have a load() method, which allows finer granularity, especially if there are perhaps multiple images to load.

  $(document).ready(function(){ 
    $("#top_img_0").load (function (){
      $("#text").append( "height: " + $("#top_img_0").attr("height")+"<br/>" );
      $("#text").append( "width: " + $("#top_img_0").attr("width")+"<br/>" );   
      }); 
  });


回答3:

It looks like it is a race condition, at least it was for me using Chrome. The image isn't finished loading at the time you are getting the dimensions. I set everything to fire after a 200ms timeout and the real width/height are displayed.

    $(document).ready(function() {
        setTimeout("getImageDimensions()", 200);
    });

    function getImageDimensions() {
        var pic_real_width;
        var pic_real_height;

        $("#topContent img").each(function() {
            var $this = $(this);
            $this.removeAttr("width");
            $this.removeAttr("height");
            $this.css({ width: 'auto', height: 'auto' });

            pic_real_width = $this.width();
            pic_real_height = $this.height();
            $this.css({ width: '', height: '100px' });
        });

        $("#text").append(" height: " + pic_real_height/*$("#top_img_0").attr("height")*/ + "<br/>");
        $("#text").append(" width: " + pic_real_width/*$("#top_img_0").attr("width")*/ + "<br/>");
    }

Tested and works in Chrome, IE and Firefox. All display 2008 x 3008.



回答4:

Replace

$this.css({width: '', height: ''}); 

with

$this.css({width: 'auto', height: 'auto'});

Opera 10.10 height/width 2008 x 3008