开发者

How to get paragraph height using jQuery?

I've been trying to use $(".someid").height() to determine the height of a paragraph using jQuery, but the result always returns 0. What gives?

<p class="someid">Blah this is a test, I am trying to see when this wraps around what hei开发者_高级运维ght it might have. I want to know how tall this paragraph element i because it can change from element to element.</p>.

I've tried using display:block in the css, or even height:auto to see if I can force CSS to consider it to be a block of text, but no results there either.

Thanks!


You are probably doing the declaration on $(document).ready(), at which time the element is not rendered on the page, so there is no height. You'll have to do it on $(window).load() at which time the paragraph element will be rendered and will have a height.


Maybe you should test the example in the jquery documentation? For example here

This one works without any problems:

<!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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜