textarea value height [duplicate]

会有一股神秘感。 提交于 2019-12-11 03:25:00

问题


I have a textarea that has a set css height of 85px. A user might type 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?


回答1:


I would duplicate the content of the textarea into another element with the same width, hidden, and then get its height.




回答2:


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 divs 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() (and height()).



回答3:


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.



来源:https://stackoverflow.com/questions/5995809/textarea-value-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!