【问题标题】:Get actual height of object whose set to "auto"获取设置为“自动”的对象的实际高度
【发布时间】:2016-10-15 18:14:32
【问题描述】:

这似乎是一个非常初级的问题,但无论我如何表达,我似乎都找不到任何人为我提供解决方案。

我有一个设置大小以适合我的布局并保持其纵横比的图像,如下所示:

img{
   width:50%;
   height:auto;
}

由于我不知道图像有多高,我必须使用图像的实际高度(通过自动调整其大小)来计算另一个元素的位置。

$("img").height();

然而,只要它设置为自动,它就会返回 0。 我错过了什么?或者我怎样才能找到设置为自动的图像的当前高度:)?

谢谢!

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

在原生 JavaScript 中:

element.offsetHeight;

要获得正确的值,请确保您的图片已加载。为此,要么使用windowload 事件,要么通过JS 使用您的图像preload。不要不要在 jQuery 中使用 documentreadyDOMContentLoaded 事件。

【讨论】:

    【解决方案2】:

    我的建议是:

    $(function () {
    
      // in jQuery you can use: 
      var h = $("img").height();
      console.log('$("img").height() is: ' + h);
      console.log('$("img").css("height") is: ' + $("img").css("height"));
      
    
      // in javascript, with the unit measure:
      // This form corresponds to the second jQuery method
      var elem = document.querySelectorAll('img')[0];
      var h1 = window.getComputedStyle(elem).height;
      console.log('window.getComputedStyle(elem).height is: ' + h1);
    });
    img{
      width:50%;
      height:auto;
    }
    <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <img src="https://www.google.it/logos/doodles/2016/karl-landsteiners-148th-birthday-5693101206142976-res.png">

    【讨论】:

      【解决方案3】:

      您可能正在使用“document ready”事件,而您应该使用load event。在图像在浏览器中呈现之前,您无法检索图像的尺寸。

      $(window).load(function() {
          $(window).resize(function() {
              console.log('Height: ' + $('img').height());
          }).resize();
      });
      img {
          width: 50%;
          height: auto;
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      
      <img src="http://lorempixel.com/200/200" height="200" width="200">

      【讨论】:

      • 不完全是。我正在寻找调整后的高度 - 而不是原来的高度。
      • @user3307017 是的。本例中图片的原始高度为 200px。
      • 尝试全屏打开您的 sn-p。即使它几乎是 2000px 高,它仍然显示 250~
      • @user3307017 在这个例子中我没有处理窗口调整大小。它仅显示加载时的图像大小.. 答案已更新
      【解决方案4】:

      我认为这会有所帮助:

      document.defaultView.getComputedStyle(document.querySelector("selector")).height;
      

      它返回一个以 px 为单位的真实高度的字符串。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-16
        • 1970-01-01
        • 2013-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多