获取动态创建的元素的高度 [英] Get height of dynamically created element

查看:76
本文介绍了获取动态创建的元素的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我动态创建了一个div并尝试获取其高度.我没有给它分配固定的高度.但是它的内容被分配了一个固定的高度.因此,我试图获得其渲染高度.

I created one div dynamically and tried to get its height. I didn't assign fixed height to it. But its content is assigned a fixed height. So I tried to get its render height.

$(function(){
    $services = $(<div id="services"></div>);
    $img  = $(<img src="abc.jpg" height="100px" width="100px">);
    $a = $("<a href="home.php">Go to home</a>");
    $services.append($img,$a);
});

$(function(){
    var height = $("#services").height();
});

我的身高值为0.

所以我不能渲染div#services的高度.

So I can't render height of div#services.

推荐答案

您需要先将元素添加到DOM中,然后再进行测量:

You need to add the element to the DOM before measuring it:

$('body').append($services);
var height = $("#services").height(); // works now

如果在使其可见之前需要其高度,一个常见的技巧是将其添加到DOM中隐藏,对其进行测量,然后使其可见.

If you need its height before making it visible, a common trick is to add it to the DOM hidden, measure it, and then make it visible.

这篇关于获取动态创建的元素的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆