最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get actual height of text inside a div - Stack Overflow

programmeradmin5浏览0评论

So I have a content-editable div that I'm adding text to. I'd like to set up a warning when a person types a certain amount. However, I have added the ability to change the font size, boldness, italics, etc. So is there a way I can get the actual height of just the text in the div, even if the text hasn't filled the entire div up?

Something like $("#my-div").textHeight() would be awesome

So I have a content-editable div that I'm adding text to. I'd like to set up a warning when a person types a certain amount. However, I have added the ability to change the font size, boldness, italics, etc. So is there a way I can get the actual height of just the text in the div, even if the text hasn't filled the entire div up?

Something like $("#my-div").textHeight() would be awesome

Share Improve this question asked Aug 11, 2014 at 23:58 jsookikijsookiki 5421 gold badge7 silver badges23 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

Or, if you are trying for the height of the entire block of text, try this: fiddle

HTML:

<div id='hold'>
    <div id='text' contenteditable>Lorem ipsum, lorem ipsum</div>
</div>
<button id='checkTextHeight'>Check Text Height</button>

CSS:

#hold {
    border: 1px solid black;
    width: 100px;
    height: 300px;
}
#text {
    min-width: 1em;
    min-height: 1em;
}

JS:

$('#checkTextHeight').click(function() {
    alert($('#text').css('height'));
});

You can encapsulate the content in a display: inline element and take it height by using jquery $('.my-inline-element').height()

Example: http://codepen.io/anon/pen/kbtEr

var size_of_text = $('#my-div').css("font-size");

that should retrieve the font-size of your div, which I'm assuming to be the height of the text.

发布评论

评论列表(0)

  1. 暂无评论