javascript 如何获取textarea的高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19684040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:28:28  来源:igfitidea点击:

How do I get the height of a textarea

javascriptjqueryhtmlcss

提问by Tone

I need to get the height of a textarea. Seemingly so simple but it's driving me mad.

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

I have been researching for ages on stackoverflow with no luck: textarea-value-heightand jquery-js-get-the-scrollbar-height-of-an-textareaand javascript-how-to-get-the-height-of-text-inside-of-a-textarea, among many others.

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

This is how it looks currently:

这是它目前的样子:

picture of a dialog window with a textarea

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

This is how I want it to look, open a full height:

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

picture of a dialog window with a textarea open at full height.

picture of a dialog window with a textarea open at full height.

Here is my html:

这是我的 html:

 <textarea id="history" class="input-xxlarge" placeholder="Enter the content ..." rows="13"></textarea>

CSS:

CSS:

 .input-xxlarge {
    display: inline-block;
    height: auto;     
    font-size: 12px;
    width: 530px;
    resize: none;
    overflow: auto;
 }

jQuery:

jQuery:

 var textarea = $('#history');

I've tried (inter alia):

我试过(除其他外):

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

Please help, I'm at my wit's end!

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

回答by Tone

Ok, I've found a solution. Whether it's the best solution, I don't know, but it works and that, frankly, is all I care about, having spent almost a day on this issue.

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

Here it is for anyone who faces the same problem:

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

  1. Select the textarea:

    var textarea = $('#history');
    
  2. Get the textarea's text:

    var text = textarea.text();
    
  3. Create a temporary div:

    var div = $('<div id="temp"></div>');
    
  4. Set the temp div's width to be the same as the textarea. Very important else the text will be all on one line in the new temp div!:

    div.css({
       "width":"530px"
    });
    
  5. Insert the text into the new temp div:

    div.text(text);
    
  6. Append it to the DOM:

    $('body').append(div);
    
  7. Get the height of the div:

    var divHeight = $('#temp').height();
    
  8. Remove the temp div from the DOM:

    div.remove();
    
  1. 选择文本区域:

    var textarea = $('#history');
    
  2. 获取 textarea 的文本:

    var text = textarea.text();
    
  3. 创建一个临时 div:

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

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

    div.text(text);
    
  6. 将其附加到 DOM:

    $('body').append(div);
    
  7. 获取div的高度:

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

    div.remove();
    

回答by Renet

Had a similar issue, in my case I wanted to have an expand button, that would toggle between two states (expanded/collapsed). After searching also for hours I finally came up with this solution:

有一个类似的问题,在我的情况下,我想要一个展开按钮,可以在两种状态(展开/折叠)之间切换。经过几个小时的搜索,我终于想出了这个解决方案:

Use the .prop to get the content height - works with dynamically filled textareas and then on a load command set it to your textarea.

使用 .prop 获取内容高度 - 与动态填充的 textareas 一起使用,然后在加载命令上将其设置为您的 textarea。

Get the inner height:

获取内部高度:

var innerHeight = $('#MyTextarea').prop('scrollHeight');

Set it to your element

将其设置为您的元素

$('#MyTextarea').height(innerHeight);

Complete code with my expand button(I had min-height set on my textarea):

使用展开按钮完成代码(我在 textarea 上设置了最小高度):

$(document).on("click", '.expand-textarea', function () {
    $(this).toggleClass('Expanded');

    if($(this).hasClass('Expanded'))
      $($(this).data('target')).height(1);
    else
      $($(this).data('target')).height($($(this).data('target')).prop('scrollHeight'));
  });

回答by Zach

Place this BEFORE any HTML elements.

将此放在任何 HTML 元素之前。

<script src="/path/to/jquery.js"></script>

<script>
$(document).ready(function(){
var textarea = $('#history');
alert(textarea.height()); //returns correct height 
});
</script>

You obviously do not have to alert it. I was just using an easily visible example.

您显然不必提醒它。我只是使用一个容易看到的例子。

回答by Jeromy French

Given a textarea with an idof "history", this jQuery will return it's height:

给定一个带有id“history”的 textarea ,这个 jQuery 将返回它的高度:

$('#history').height()

Please see a working example at http://jsfiddle.net/jhfrench/JcGGR/

在 http://jsfiddle.net/jhfrench/JcGGR/查看一个工作示例

回答by D4V1D

You can also retrieve the height in pixels by using $('#history').css('height');if you're not planning on doing any calculations.

$('#history').css('height');如果您不打算进行任何计算,您还可以通过使用来检索以像素为单位的高度。

回答by amcgregor

Modern answer: textareasizing is a few lines of ES6 implementable two primary ways. It does notrequire (or benefit from) jQuery, nor does it require duplication of the content being sized.

现代答案:textarea调整大小是 ES6 的几行可实现的两种主要方式。它要求(或利益)的jQuery,也不需要在内容部的尺寸的重复。

As this is most often required to implement the functionality of auto-sizing, the code given below implements this feature. If your modal dialog containing the text area is not artificially constrained, but can adapt to the inner content size, this can be a perfect solution. E.g. don't specify the modal body's height and remove overflow-ydirectives. (Then no JS will be required to adjust the modal height at all.)

由于这通常是实现自动调整大小的功能所必需的,因此下面给出的代码实现了此功能。如果您的包含文本区域的模态对话框没有人为限制,但可以适应内部内容大小,这可能是一个完美的解决方案。例如,不要指定模态主体的高度和删除overflow-y指令。(然后根本不需要 JS 来调整模态高度。)

See the final section for additional details if you really, truly only actually need to fetch the height, not adapt the height of the textareaitself.

如果您真的真的只需要获取高度,而不是调整textarea自身的高度,请参阅最后一节以获取更多详细信息。

Line–Based

基于线

Pro:almost trivial. Pro:exploits existing user-agent behavior which does the heavy lifting (font metric calculations) for you. Con:impossible to animate. Con:extended to support constraints as per my codepen used to explore this problem, constraints are encoded into the HTML, not part of the CSS, as data attributes.

亲:几乎微不足道。 优点:利用现有的用户代理行为,为您完成繁重的工作(字体度量计算)。 缺点:无法制作动画。 Con:根据我用来探索这个问题的 codepen扩展为支持约束,约束被编码到 HTML 中,而不是 CSS 的一部分,作为数据属性。

/* Lines must not wrap using this technique. */
textarea { overflow-x: auto; white-space: nowrap; resize: none }
for ( let elem of document.getElementsByTagName('textarea') ) {
    // Prevent "jagged flashes" as lines are added.
    elem.addEventListener('keydown', e => if ( e.which === 13 ) e.target.rows = e.target.rows + 1)

    // React to the finalization of keyboard entry.
    elem.addEventListener('keyup', e => e.target.rows = (elem.value.match(/\n/g) || "").length + 1)
}

Scrollable Region–Based

基于可滚动区域

Pro:still almost trivial. Pro:animatable in CSS (i.e. using transition), though with some mild difficulty relating to collapsing back down. Pro:constraints defined in CSS through min-heightand max-height. Con:unless carefully calculated, constraints may crop lines.

亲:仍然几乎微不足道。 优点可在 CSS 中设置动画(即使用transition),但在折叠时会遇到一些轻微的困难。 优点:通过min-height和定义在 CSS 中的约束max-height缺点:除非仔细计算,否则约束可能会裁剪线条。

for ( let elem of document.getElementsByTagName('textarea') )
    elem.addEventListener('keyup', e => {
        e.target.style.height = 0  // SEE NOTE
        e.target.style.height = e.target.scrollHeight + 'px'
    })

A shocking percentage of the search results utilizing scrollHeightnever consider the case of reducing size; for details, see below. Or they utilize events "in the wrong order" resulting in an apparent delay between entry and update, e.g. pressing enter… then any other key in order to update. Example.

令人震惊的搜索结果比例scrollHeight从未考虑过减小大小的情况;有关详细信息,请参见下文。或者他们“以错误的顺序”利用事件导致进入和更新之间的明显延迟,例如按回车...然后按任何其他键以进行更新。 例子。

Solution to Initial Question

初始问题的解决方案

The initial question specifically related to fetching the height of a textarea. The second approach to auto-sizing, there, demonstrates the solution to that specific question in relation to the actual content. scrollHeightcontains the height of the element regardless of constraint, e.g. its inner content size.

最初的问题与获取 textarea 的高度有关。第二种自动调整大小的方法演示了与实际内容相关的特定问题的解决方案。 scrollHeight包含元素的高度而不考虑约束,例如其内部内容大小。

Note:scrollHeight is technically the Math.max()of the element's outer height orthe inner height, whichever is larger. Thus the initial assignment of zero height. Without this, the textareawould expand, but never collapse. Initial assignment of zero ensures you retrieve the actual inner content height. For sampling without alteration, remove the height override (assign '') or preserve (prior to) then restore after retrieval of scrolllHeight.

注意:scrollHeight 在技术上是Math.max()元素的外部高度内部高度,以较大者为准。因此初始赋值为零高度。没有这个,它textarea会膨胀,但永远不会崩溃。零的初始分配可确保您检索实际的内部内容高度。对于不更改的采样,删除高度覆盖(分配'')或保留(之前)然后在检索后恢复scrolllHeight

To calculate just the height of the element as-is, utilize getComputedStyleand parse the result:

要按原样计算元素的高度,请利用getComputedStyle并解析结果:

parseInt(getComputedStyle(elem).height, 10)

But really, please consider just adjusting the CSS to permit the modal to expand naturally rather than involving JavaScript at all.

实际上,请考虑只调整 CSS 以允许模态自然扩展,而不是完全涉及 JavaScript。