简体   繁体   English

我如何获得文本区域的高度

[英]How do I get the height of a textarea

I need to get the height of a textarea.我需要获取文本区域的高度。 Seemingly so simple but it's driving me mad.看似如此简单,但它让我发疯。

I have been researching for ages on stackoverflow with no luck: textarea-value-height and jquery-js-get-the-scrollbar-height-of-an-textarea and 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:这是它目前的样子:

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

This is how I want it to look, open a 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:查询:

 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!请帮忙,我已经无计可施了!

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:获取 textarea 的文本:

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

     var div = $('<div id="temp"></div>');
  4. Set the temp div's width to be the same as the textarea.将临时 div 的宽度设置为与 textarea 相同。 Very important else the text will be all on one line in the new temp div!:非常重要的是,文本将全部位于新临时 div 中的一行中!:

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

     div.text(text);
  6. Append it to the DOM:将其附加到 DOM:

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

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

     div.remove();

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 获取内容高度 - 使用动态填充的文本区域,然后在加载命令上将其设置为您的文本区域。

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'));
  });

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.我只是使用一个容易看到的例子。

Given a textarea with an id of "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/ 上的工作示例

You can also retrieve the height in pixels by using $('#history').css('height');您还可以使用$('#history').css('height');检索以像素为单位$('#history').css('height'); if you're not planning on doing any calculations.如果您不打算进行任何计算。

Modern answer: textarea sizing is a few lines of ES6 implementable two primary ways.现代答案: textarea大小调整是 ES6 的几行可实现的两种主要方式。 It does not require (or benefit from) jQuery, nor does it require duplication of the content being sized.要求(或利益)的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.如果您的包含文本区域的模态对话框没有人为限制,但可以适应内部内容大小,这可能是一个完美的解决方案。 Eg don't specify the modal body's height and remove overflow-y directives.例如,不要指定模态主体的高度并删除overflow-y指令。 (Then no JS will be required to adjust the modal height at all.) (然后根本不需要 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 textarea itself.如果您真的真的只需要获取高度,而不是调整textarea本身的高度,请参阅最后一节以获取更多详细信息。

Line–Based基于线

Pro: almost trivial.亲:几乎微不足道。 Pro: exploits existing user-agent behavior which does the heavy lifting (font metric calculations) for you. Pro:利用现有的用户代理行为,为您完成繁重的工作(字体度量计算)。 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 (ie using transition ), though with some mild difficulty relating to collapsing back down.优点可在 CSS 中设置动画(即使用transition ),但在折叠时有一些轻微的困难。 Pro: constraints defined in CSS through min-height and max-height . Pro:通过min-heightmax-height在 CSS 中定义的约束。 Con: unless carefully calculated, constraints may crop lines.缺点:除非仔细计算,否则约束可能会裁剪线条。

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 scrollHeight never consider the case of reducing size;使用scrollHeight的搜索结果中有惊人的百分比从未考虑过减小尺寸的情况; for details, see below.有关详细信息,请参见下文。 Or they utilize events "in the wrong order" resulting in an apparent delay between entry and update, eg pressing enter… then any other key in order to update.或者他们“以错误的顺序”利用事件,导致进入和更新之间的明显延迟,例如按回车...然后按任何其他键以进行更新。 Example.例子。

Solution to Initial Question初始问题的解决方案

The initial question specifically related to fetching the height of a textarea.最初的问题特别与获取 textarea 的高度有关。 The second approach to auto-sizing, there, demonstrates the solution to that specific question in relation to the actual content.第二种自动调整大小的方法演示了与实际内容相关的特定问题的解决方案。 scrollHeight contains the height of the element regardless of constraint, eg its inner content size. scrollHeight包含元素的高度,而不考虑约束,例如其内部内容大小。

Note: scrollHeight is technically the Math.max() of the element's outer height or the inner height, whichever is larger.注意: scrollHeight 在技术上是元素外部高度内部高度的Math.max() ,以较大者为准。 Thus the initial assignment of zero height.因此初始赋值为零高度。 Without this, the textarea would expand, but never collapse.没有这个, textarea会扩展,但永远不会崩溃。 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 .对于不更改的采样,删除高度覆盖(分配'' )或保留(之前)然后在检索scrolllHeight后恢复。

To calculate just the height of the element as-is , utilize getComputedStyle and 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。

for current height in px:对于当前高度(以 px 为单位):


height = window.getComputedStyle(document.querySelector('textarea')).getPropertyValue('height')

for current width in px:当前宽度 px:


width = window.getComputedStyle(document.querySelector('textarea')).getPropertyValue('width')

change 'textarea' to '#history' or like a css selector.'textarea'更改为'#history'或类似于 css 选择器。 or textarea , since a variable is declared to select element.textarea ,因为声明了一个变量来选择元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM