Jquery - 获取构造div的高度

Max*_*Max 7 html jquery

我正在构建一个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>
Run Code Online (Sandbox Code Playgroud)

在我的身体标签,

<body>
<div id="page"></div>
</body>
Run Code Online (Sandbox Code Playgroud)

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

Ric*_*ton 8

未添加到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();
});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/MPtvK/


Mur*_*aza 6

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

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

如果你仍然想要获得高度,我可以建议你在html临时放置div,你可以附加你当前的div并检查高度.如果你想要你并将div追加到你想要的地方.

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