textarea value height [duplicate]
I have a textarea that has a set css height of 85px. A user might ty开发者_如何转开发pe lines of content within that textarea, and I would like to know how high the text/val is, NOT the text area itself.
Is there a way to check the height of the inside text including line breaks?
I would duplicate the content of the textarea into another element with the same width, hidden, and then get its height.
This is how I'd do it, though obviously the mark-up is only generic and to be amended to your needs:
html
<div class="counter"></div>
<textarea></textarea>
<div class="tmp"></div>
CSS
textarea, div {
width: 150px;
resize: none;
border: 1px solid #ccc;
padding: 0;
margin: 0;
font-size: 1em;
font-family: Arial, sans-serif;
}
textarea {
height: 85px;
}
div {
min-height: 85px;
}
jQuery:
$('textarea').keyup(
function(e){
var t = $(this).val();
$(this).next('.tmp').text(t);
$(this).prev('.counter').text('Height is: ' + $(this).next('.tmp').outerHeight());
});
JS Fiddle demo.
This could be amended to dynamically add, and remove, the .tmp
div
s as required. But I was trying to keep this as simple as possible, so I left it hard-coded.
References:
keyup()
.val()
.next()
.prev()
.text()
.outerHeight()
(andheight()
).
I'm not sure exactly why you're wanting to do this. If you are just trying to have the box increase in size to match the text, use one of many extensions such as:
http://unwrongest.com/projects/elastic/
If this isn't what you're looking for, you can have a look at the source and see how they achieve this, and mimic it.
精彩评论