【问题标题】:can't get true height/width of object in chrome无法在 chrome 中获得对象的真实高度/宽度
【发布时间】:2011-01-30 20:55:00
【问题描述】:

我有一个问题,如果我在 css 中设置图像高度并尝试获取高度/宽度,我会在不同的浏览器中得到不同的结果。有没有办法在所有浏览器中获得相同的维度?

你可以找到一个活生生的例子here

这个概念是这样的:

CSS:
img{
  height:100px;
  }

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

输出火狐: 图片高度:100 图片宽度:150

输出铬: 图片高度:100 图片宽度:0

输出铬: 图片高度:100 图片宽度:93?

我已经从 StackOverflow 尝试过: stackoverflow.com/questions/1873419/jquery-get-height-width

但仍然得到相同的结果

任何人都知道一个好的解决方案?

【问题讨论】:

    标签: jquery google-chrome height width


    【解决方案1】:

    图片未在document.ready 中加载,您需要使用window.load 事件来确保它们存在,如下所示:

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

    Here's a quick read on the difference,重要的是图片加载完毕。

    【讨论】:

    【解决方案2】:

    Nick Craver 对使用 $(window).load() 的回答是正确的,但图像也有一个 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】:

      看起来这是一个竞争条件,至少对我使用 Chrome 来说是这样。在您获取尺寸时,图像尚未完成加载。我将所有内容设置为在 200 毫秒超时后触发并显示实际宽度/高度。

          $(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/>");
          }
      

      在 Chrome、IE 和 Firefox 中测试并运行。全部显示 2008 x 3008。

      【讨论】:

      • 尝试超时提供了关于为什么事情不工作的线索,但是以这种方式修复竞争条件只会将其变成不同的竞争条件。 IE。它现在可以在您的高速连接上工作,但不能在较慢的连接上工作。
      【解决方案4】:

      替换

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

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

      Opera 10.10 高/宽 2008 x 3008

      【讨论】:

      • 我已经测试过了,但没有帮助,Chrome 4.1 高度/宽度 0 x 0
      猜你喜欢
      • 2021-05-09
      • 1970-01-01
      • 2021-07-14
      • 2010-09-17
      • 1970-01-01
      • 2010-09-24
      • 2017-04-11
      • 1970-01-01
      相关资源
      最近更新 更多