2011-05-26 58 views
2

我一直试图使用$(“。someid”)。height()来确定使用jQuery的段落的高度,但结果总是返回0.什么给了?如何使用jQuery获取段落高度?

<p class="someid">Blah this is a test, I am trying to see when this wraps around what height it might have. I want to know how tall this paragraph element i because it can change from element to element.</p>.

我试着使用display:block在CSS,甚至height:auto,看看我是否可以强制CSS把它看作是一个文本块,但没有结果有两种。

谢谢!

+1

Hmn ...适合我。 http://jsfiddle.net/2NKx6/ – Larsenal 2011-05-26 21:21:38

+0

你可以把你的代码放在jsfiddle中吗? – cmplieger 2011-05-26 21:24:24

回答

2

你可能做的$声明(文件)。就绪(),此时该元素没有显示在页面上呈现,所以没有高度。您必须在$(window).load()上执行此操作,届时将显示段落元素并将具有高度。

+4

希望没有人会犯我犯的愚蠢错误!这是'$(function(){});' – Rio 2011-05-26 21:32:23

+1

我讨厌重复别人的错误。我努力做出新的。 – Yisroel 2011-05-26 21:34:13

0

也许你应该在jQuery文档中测试示例?例如here

这一个工作没有任何问题:

<!DOCTYPE html> 
<html> 
<head> 
    <style> 
    body { background:yellow; } 
    button { font-size:12px; margin:2px; } 
    p { width:150px; border:1px red solid; } 
    div { color:red; font-weight:bold; } 
    </style> 
    <script src="http://code.jquery.com/jquery-latest.js"></script> 
</head> 
<body> 
    <button id="getp">Get Paragraph Height</button> 
    <button id="getd">Get Document Height</button> 
    <button id="getw">Get Window Height</button> 

    <div>&nbsp;</div> 
    <p> 
    Sample paragraph to test height 
    </p> 
<script> 
    function showHeight(ele, h) { 
     $("div").text("The height for the " + ele + 
        " is " + h + "px."); 
    } 
    $("#getp").click(function() { 
     showHeight("paragraph", $("p").height()); 
    }); 
    $("#getd").click(function() { 
     showHeight("document", $(document).height()); 
    }); 
    $("#getw").click(function() { 
     showHeight("window", $(window).height()); 
    }); 

</script> 

</body> 
</html>