【问题标题】:Height of DIV not calculated correctly if text insides wraps on document load如果文本内部在文档加载时换行,则 DIV 的高度计算不正确
【发布时间】:2018-07-24 04:27:02
【问题描述】:

我有一个 div。

<div id="test">this is a lot of text and more and more and more and more and more and more and more and more text</div>

在 document.ready 上,我正在获取 div 的高度。

$(document).ready(function() {
  var intDivHeight = $("#test").outerHeight(true);
});

如果我将浏览器窗口扩大到非常宽以使文本不换行并重新加载页面,则高度为 32。如果我将浏览器窗口缩小以使文本换行为两三行,则高度还是 32 岁。

奇数。

如果我将上面的代码放在 window.resize 函数中,我会在初始页面加载时得到错误的大小,但我会在开始调整窗口大小时得到正确的大小。

$(window).resize(function() {
  var intDivHeight = $("#test").outerHeight(true);
});

在调整大小时,32 变为 56 或 78。

奇数。

有人可以向我解释为什么会发生这种情况吗?而且,是否有解决方案让我可以在 document.ready 上获得正确的“包装”高度?我正在使用它来尝试使用 JavaScript 定位某些元素。

谢谢!

【问题讨论】:

    标签: javascript jquery height word-wrap


    【解决方案1】:

    您可以通过简单的 ol' javascript 获取 scrollHeight!或者,如果您打算在 div 中包含溢出内容,则可以坚持使用 jQuery outerHeight() 函数。

    至于报告页面加载与调整大小的数字,您需要绑定 2 个事件处理程序才能这样做。第一个在load,第二个在resize

    我可以举个简单的例子:

    $(function() {
    
      $(window).on("load resize", function() {
        console.log("Our height is " + $("div")[0].scrollHeight);
      });
      
    });
    div {
    background-color: #f1f1f1;
    padding: 10px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div>Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text!</div>

    【讨论】:

    • 窗口加载事件是解决方案的关键。我正在使用 jQ 3,因此我无法再绑定文档就绪和窗口调整大小事件。我根据需要将它们分开,但增加了负载并且效果很好。谢谢!
    • 太好了,很高兴听到它!
    【解决方案2】:

    您可以通过绑定窗口loadresize 事件来做到这一点。

    var intDivHeight;
    
    $(document).ready(function() {
      $(window).on("load resize", function() {
        intDivHeight = $("#test").outerHeight(true);
      });
    });
    

    【讨论】:

    • 你们俩都有相同的解决方案。我不得不把它给第一个人。谢谢!
    猜你喜欢
    • 2013-05-01
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    • 2014-06-02
    相关资源
    最近更新 更多