如何获取textarea的高度

Ton*_*one 1 html javascript css jquery

我需要获取文本区域的高度。看起来很简单,但它让我发疯。

我一直在研究 stackoverflow 没有运气:textarea-value-heightjquery-js-get-the-scrollbar-height-of-an-textareajavascript-how-to-get-the-height-of- text-inside-of-a-textarea等等。

这是它目前的样子:

带有文本区域的对话窗口的图片

这就是我想要它的外观,打开一个完整的高度:

文本区域全高打开的对话框窗口的图片.

这是我的 html:

 <textarea id="history" class="input-xxlarge" placeholder="Enter the content ..." rows="13"></textarea>
Run Code Online (Sandbox Code Playgroud)

CSS:

 .input-xxlarge {
    display: inline-block;
    height: auto;     
    font-size: 12px;
    width: 530px;
    resize: none;
    overflow: auto;
 }
Run Code Online (Sandbox Code Playgroud)

jQuery:

 var textarea = $('#history');
Run Code Online (Sandbox Code Playgroud)

我试过(除其他外):

1. textarea.height() --> always returns 0
2. textarea.ready(function() { // wait for DOM to load
      textarea.height();
   }
3. getting scrollheight from textarea as an HTMLTextareaElement (i.e. DOM Element) --> returns 0
4. var contentSpan = textarea.wrapInner('<span>');
   var height = contentSpan.height(); --> always returns 0
Run Code Online (Sandbox Code Playgroud)

请帮助我,我的智商已尽!

Ton*_*one 5

好的,我找到了解决方案。我不知道这是否是最好的解决方案,但它确实有效,坦率地说,这就是我关心的全部,在这个问题上花了将近一天的时间。

这是为任何面临同样问题的人准备的:

  1. 选择文本区域:

    var textarea = $('#history');
    
    Run Code Online (Sandbox Code Playgroud)
  2. 获取 textarea 的文本:

    var text = textarea.text();
    
    Run Code Online (Sandbox Code Playgroud)
  3. 创建一个临时 div:

    var div = $('<div id="temp"></div>');
    
    Run Code Online (Sandbox Code Playgroud)
  4. 将临时 div 的宽度设置为与 textarea 相同。非常重要的是,文本将全部位于新临时 div 中的一行中!:

    div.css({
       "width":"530px"
    });
    
    Run Code Online (Sandbox Code Playgroud)
  5. 将文本插入到新的临时 div 中:

    div.text(text);
    
    Run Code Online (Sandbox Code Playgroud)
  6. 将其附加到 DOM:

    $('body').append(div);
    
    Run Code Online (Sandbox Code Playgroud)
  7. 获取div的高度:

    var divHeight = $('#temp').height();
    
    Run Code Online (Sandbox Code Playgroud)
  8. 从 DOM 中删除临时 div:

    div.remove();
    
    Run Code Online (Sandbox Code Playgroud)