【问题标题】:Jquery - Getting height of the constructed divJquery - 获取构造的div的高度
【发布时间】:2013-12-19 08:54:57
【问题描述】:

我正在构建一个 div 并将其附加到一个主 div。在执行此操作时,我需要在构建 div 并添加它之前立即获取它的高度。

例如,

<script>
$(function(){
var text = $("#ObjText").html(); // This text is dynamic

var dv = $("<div id='childDiv'>"+text+"</div>");
alert($(dv).height()); // This is getting '0' - Need to get the height of the div here.

$("#page").append(dv);

//After appending to page able to get the height of the child div
alert($("#childDiv").height());
});
</script>

在我的身体标签中,

<body>
<div id="page"></div>
</body>

请帮我解决这个问题。提前致谢。

【问题讨论】:

    标签: jquery html


    【解决方案1】:

    没有添加到dom的div没有高度。

    你可以做的是隐藏 div,然后附加它并获取高度,然后显示 div:

    $(function(){
        var text = $("#ObjText").html(); // This text is dynamic
    
        var dv = $("<div id='childDiv'>"+text+"</div>").hide(); // hide the div
    
        $("#page").append(dv);
        alert(dv.height());  // should have the correct height
    
        dv.show();
    });
    

    http://jsfiddle.net/MPtvK/

    【讨论】:

      【解决方案2】:

      我认为在将其附加到文档之前,您无法获取在运行时创建的任何对象的高度。

      jQuery 执行并获取文档(您的 html)上所有可用的 DOM 就绪对象的结果,因此在附加之前您无法获得高度。

      如果您仍想获得高度,我可以建议您在 html 上临时放置 div,您可以在其中附加当前 div 并检查高度。如果你想要你,然后在你想要的地方追加 div。

      希望以上内容能帮助您找到解决方案...

      【讨论】:

      • 该死的我完全错过了它,这是有道理的,谢谢 Murtaza。
      【解决方案3】:

      style="display: none"插入,然后使用普通jquery .height() 获取高度。需要时使用 .show() 显示。

      【讨论】:

      • 当您显示:无时,您将取消布局。
      猜你喜欢
      • 1970-01-01
      • 2014-01-19
      • 2014-09-06
      • 2012-02-08
      • 1970-01-01
      • 1970-01-01
      • 2011-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多