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

后端 未结 4 1344
囚心锁ツ
囚心锁ツ 2021-02-06 03:20

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 brow

4条回答
  •  梦谈多话
    2021-02-06 03:43

    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")*/ + "
    "); $("#text").append(" width: " + pic_real_width/*$("#top_img_0").attr("width")*/ + "
    "); }

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

提交回复
热议问题