当您键入文本时会扩展的 CSS 文本区域

发布于 2024-10-17 03:44:32 字数 95 浏览 5 评论 0原文

我有一个文本区域,用户可以在其中输入文本。默认情况下,它的高度为 17px。但是,如果用户插入大量文本,我希望文本区域相应地扩展。有没有办法用 CSS 做到这一点?提前致谢!!

I have a Textarea where users can input text. By default it has a height of 17px. However if users insert a large amount of text, I want the text area to expand accordingly. Is there a way to do this with CSS ? Thanks in advance!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

凉薄对峙 2024-10-24 03:44:32

我知道这有点晚了,但我不得不说有一种方法可以使用

contenteditable 属性来模拟所需的行为。

.textareaElement {
  width: 300px;
  min-height: 17px;
  border: 1px solid #ccc;
  max-height: 150px;
  overflow-x: hidden;
  overflow-y: auto;
}
<div class="textareaElement" contenteditable></div>

只需设置最小和最大高度,并使用适当的溢出值,您就拥有功能齐全的纯 CSS 扩展文本框,这也得到了很好的支持。

输入图像描述这里

I know this is a little bit late, but I have to say there is a way to use <div> with contenteditable attribute to simulate desired behaviour.

.textareaElement {
  width: 300px;
  min-height: 17px;
  border: 1px solid #ccc;
  max-height: 150px;
  overflow-x: hidden;
  overflow-y: auto;
}
<div class="textareaElement" contenteditable></div>

Just set your min and max height, with proper overflow values, and you have fully functional pure CSS expanding textbox, that is also well supported.

enter image description here

生生不灭 2024-10-24 03:44:32

仅靠 CSS 无法做到这一点。尝试使用自动增长 jquery 插件。
https://github.com/jaz303 /jquery-grab-bag/blob/master/javascripts/jquery.autogrow-textarea.js

您还可以在此处查看自动增长演示 http://onehackoranother.com/projects/jquery/jquery-grab-bag/autogrow-textarea.html

它轻量级且易于使用。这是如何完成的。定义您的文本区域 ID。在 之前包含 jquery js 文件。然后在脚本标签之间发出 jquery 命令 $("#txtInput").autoGrow();

<body>
    <textarea id="txtInput"></textarea>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script> 

<script>
    $("#txtInput").autogrow();
</script>
</body>

This cannot be done with CSS alone. try the autogrow jquery plugin.
https://github.com/jaz303/jquery-grab-bag/blob/master/javascripts/jquery.autogrow-textarea.js

You can also see autogrow demo here http://onehackoranother.com/projects/jquery/jquery-grab-bag/autogrow-textarea.html

It's lightweight and easy to use. Here's how it's done. Define your textarea id. Include the jquery js file before </body>. Then between script tags, issue the jquery command $("#txtInput").autoGrow();

<body>
    <textarea id="txtInput"></textarea>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script> 

<script>
    $("#txtInput").autogrow();
</script>
</body>
沉鱼一梦 2024-10-24 03:44:32

这个 jQuery 插件真的很棒:
http://www.jacklmoore.com/autosize

我已经测试了其中的一些,这是迄今为止最好的。还给出了一个使用 CSS 过渡效果的示例,该效果非常流畅。

This jQuery plugin is a really great one:
http://www.jacklmoore.com/autosize

I've tested a bunch of these and this is by far the nicest. Also gives an example of using a CSS transition effect which is pretty slick.

网名女生简单气质 2024-10-24 03:44:32

**请注意,这与上面 Woody 的答案非常相似,但希望对其进行一些扩展,并提供一个正在运行的代码示例,因为 Stack 允许我们嵌入它们。

在阅读了所有这些内容并尝试了几个插件后,我发现这些插件都没有像我希望的那样工作。我使用 jquery 执行了以下操作,但可以通过抓取填充值而不是使用内部高度来使用 javascript 轻松完成:

  • 在 CSS 中设置 textarea 的最小高度
  • 将垂直滚动的溢出设置为隐藏(我只是想垂直扩展)
  • 如果滚动高度高于高度 + 填充(innerHeight),则将高度设置为滚动高度减去每个 keyup 事件上的填充。
  • 如果滚动高度不更高,我将高度重新设置为 1,然后将高度设置为滚动高度减去填充(以缩小高度)。如果您最初不重置为较小的高度,则滚动高度不会缩小。
$(function() {
  $('#myTextArea').on('input keyup paste', function() {
    var $el = $(this),
        offset = $el.innerHeight() - $el.height();

    if ($el.innerHeight() < this.scrollHeight) {
      // Grow the field if scroll height is smaller
      $el.height(this.scrollHeight - offset);
    } else {
      // Shrink the field and then re-set it to the scroll height in case it needs to shrink
      $el.height(1);
      $el.height(this.scrollHeight - offset);
    }
  });
});
#myTextArea {
  width: 250px;
  min-height: 35px;
  overflow-y: hidden;
}
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<textarea id="myTextArea" placeholder="Hit enter a few times, it should expand"></textarea>

**Note this is very similar to Woody's answer above but wanted to expand upon it a little and provide a running code example now that Stack allows us to embed them.

After reading through all of this and trying a couple of plugins, I found that none of this quite worked as I had hoped. I did the following using jquery, but can be done with javascript just as easily by grabbing the padding values instead of using inner height:

  • Set a minimum height on the textarea in CSS
  • Set overflow to hidden for vertical scrolling (I just wanted to expand vertically)
  • Set the height to the scroll height less padding on each keyup event if scroll height was higher than height + padding (innerHeight).
  • If scroll height was not taller, I re-set the height to 1, and then set the height to the scroll height less padding (to shrink the height). If you don't reset to a smaller height initially the scroll height won't shrink.

$(function() {
  $('#myTextArea').on('input keyup paste', function() {
    var $el = $(this),
        offset = $el.innerHeight() - $el.height();

    if ($el.innerHeight() < this.scrollHeight) {
      // Grow the field if scroll height is smaller
      $el.height(this.scrollHeight - offset);
    } else {
      // Shrink the field and then re-set it to the scroll height in case it needs to shrink
      $el.height(1);
      $el.height(this.scrollHeight - offset);
    }
  });
});
#myTextArea {
  width: 250px;
  min-height: 35px;
  overflow-y: hidden;
}
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<textarea id="myTextArea" placeholder="Hit enter a few times, it should expand"></textarea>

装纯掩盖桑 2024-10-24 03:44:32

您不需要为此使用插件。这适用于任何大小、高度或行大小的文本区域,并且仅当内容超出文本区域时才有效。首先将目标文本区域上的溢出设置为隐藏并将大小调整为无,然后将以下功能添加到要自动增长的文本区域。它不仅会随着用户输入而增加文本区域的大小,还会在用户删除内容时自动缩小文本区域。

$('textarea').on('paste input', function () {
    if ($(this).outerHeight() > this.scrollHeight){
        $(this).height(1)
    }
    while ($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))){
        $(this).height($(this).height() + 1)
    }
});

它的工作原理是测量文本区域的滚动高度是否大于外部高度,只有当文本数量超过文本区域可以容纳的数量时才会出现这种情况 - 并且它会考虑边框大小以获得更高的精度。使用粘贴和输入意味着只有当用户实际更改文本区域的值时(而不是按任意键),它才会增加。它很小,但当有人按箭头键或其他键时,文本区域不应该增长。

明智的做法可能是添加一个“No JS”选项,为那些没有 Javascript 的人重新启用溢出和调整大小,否则他们将被困在一个小盒子里。

You don't need a plugin for this. This works on textareas of any size, height or row size and will only work when the contents exceeds the textarea. Firstly set the overflow on your target textareas to hidden and resize to none, then add the following functionality to the textareas you want to autogrow. Not only will it increase the textarea's size as the user types, it'll also auto-shrink it when they delete stuff.

$('textarea').on('paste input', function () {
    if ($(this).outerHeight() > this.scrollHeight){
        $(this).height(1)
    }
    while ($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))){
        $(this).height($(this).height() + 1)
    }
});

It works by measuring if the scroll height of the textarea is bigger than the outer height, which it only will be if there's more text than the textarea can hold - and it takes border size into account for higher accuracy. Using paste and input means it will only increase when the user physically changes the value of the textarea, as opposed to when they press any key. It's petty but a textarea shouldn't grow when somebody presses an arrow key or something.

It might be prudent to add a No JS option that re-enables overflow and resizing for those who don't have Javascript, else they'll be stuck with a tiny box.

通知家属抬走 2024-10-24 03:44:32

为此使用 JavaScript。

此脚本会在每次击键后检查文本区域的长度(来自 此处的复制粘贴< /a>):

  <textarea name="x" onKeyUp="SetNewSize(this);" cols="5" rows="4"></textarea>
    <script language="javascript">
    function SetNewSize(textarea){
      if (textarea.value.length > 5){
        textarea.cols = 50;
        textarea.rows = 50;
      }  else{
         textarea.cols = 10;
         textarea.rows = 15;
      }
    }
  </script>

Use JavaScript for this.

This script checks the lenth of text area after every keystroke there (copypasta from here):

  <textarea name="x" onKeyUp="SetNewSize(this);" cols="5" rows="4"></textarea>
    <script language="javascript">
    function SetNewSize(textarea){
      if (textarea.value.length > 5){
        textarea.cols = 50;
        textarea.rows = 50;
      }  else{
         textarea.cols = 10;
         textarea.rows = 15;
      }
    }
  </script>
迷雾森÷林ヴ 2024-10-24 03:44:32

有点晚了,但这对我来说就像一个魅力,它是在jquery中:

这个textarea的限制高度为200px,起始高度为22px。填充对于将文本保持在合适的位置很有帮助,但是,我们必须根据字体的大小来调整权重。

另一个问题有类似的答案,但这个答案更完整一些。

$('textarea').each(function () {
  // Do something if you want
}).on('input', function () {
  this.style.height = 'auto';
  // Customize if you want
  this.style.height = (this.scrollHeight - 30) + 'px'; //The weight is 30
});
textarea{
    padding: 7px;
    width: 50%;
    height: 22px;
    max-height: 200px;
    resize: none;
    overflow-y: scroll;
    font-size: 16px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Textarea:</div>
<textarea></textarea>

A little bit late, but this worked for me like a charm, it's in jquery:

This textarea have a limit height of 200px, and a starting height of 22px. The padding helps a lot to keep the text in a good place, but, we have to play with weights depending on the size of the font.

There is a similar answer in another question, but this one is a little bit more complete.

$('textarea').each(function () {
  // Do something if you want
}).on('input', function () {
  this.style.height = 'auto';
  // Customize if you want
  this.style.height = (this.scrollHeight - 30) + 'px'; //The weight is 30
});
textarea{
    padding: 7px;
    width: 50%;
    height: 22px;
    max-height: 200px;
    resize: none;
    overflow-y: scroll;
    font-size: 16px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Textarea:</div>
<textarea></textarea>

白况 2024-10-24 03:44:32

键入时展开文本区域

在文本区域中键入内容以查看效果

<script>    
function increseRows(selector)
{
    $(selector).attr("rows", $(selector).val().split("\n").length+1||2);
}
</script>

输入时扩展文本区域

Expanding textarea as you type

Type something in textarea to see the effect

<script>    
function increseRows(selector)
{
    $(selector).attr("rows", $(selector).val().split("\n").length+1||2);
}
</script>

expanding textarea as you type

隔纱相望 2024-10-24 03:44:32

我使用以下内容(当然使用 jQuery):

$(function () {
    'use strict';
    $("textarea").on('change keyup paste input', function () {
        $(this).attr("rows", Math.max($(this).val().split("\n").length || 1, $(this).attr("rows") || 1));
        $(this).css("width", $(this).css("width"));
    }).trigger('change');
});

请注意,它响应各种事件,仅增加行数(即不会减少),触发初始更改(例如,在浏览回包含大量行的表单时调整大小)线)

I use the following (with jQuery of course):

$(function () {
    'use strict';
    $("textarea").on('change keyup paste input', function () {
        $(this).attr("rows", Math.max($(this).val().split("\n").length || 1, $(this).attr("rows") || 1));
        $(this).css("width", $(this).css("width"));
    }).trigger('change');
});

Note that it responds to various events, only increases the number of lines (i.e. doesn't decrease), triggers an initial change (e.g. to resize when browsing back to a form with lots of lines)

后来的我们 2024-10-24 03:44:32

这似乎更有效并且可以处理最大高度

$(ctrl).on('paste input', function () {
    var dyLineHeight, dyMax, dyHeight;        
    if ($(this).outerHeight() > this.scrollHeight)
        $(this).height($(this).outerHeight() - parseFloat($(this).css("borderBottomWidth")) - parseFloat($(this).css("borderTopWidth")));
    dyLineHeight = Math.max(3, parseInt($(this).css("line-height")));
    dyMax = parseInt($(this).css("max-height"));
    while ($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth")))
        {
        dyHeight = $(this).height();
        if (dyHeight >= dyMax)
            break;
        $(this).height(dyHeight + dyLineHeight)
        }
});

This seems to be much more efficient and handles max-height

$(ctrl).on('paste input', function () {
    var dyLineHeight, dyMax, dyHeight;        
    if ($(this).outerHeight() > this.scrollHeight)
        $(this).height($(this).outerHeight() - parseFloat($(this).css("borderBottomWidth")) - parseFloat($(this).css("borderTopWidth")));
    dyLineHeight = Math.max(3, parseInt($(this).css("line-height")));
    dyMax = parseInt($(this).css("max-height"));
    while ($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth")))
        {
        dyHeight = $(this).height();
        if (dyHeight >= dyMax)
            break;
        $(this).height(dyHeight + dyLineHeight)
        }
});
才能让你更想念 2024-10-24 03:44:32

我一直在寻找纯js解决方案(项目中没有jquery)并最终编写了自己的解决方案。它非常快,没有兼容性问题,并且不需要额外的库。

需要注意的一个细节是,您需要在新字符出现之前放大框的大小,但在字符消失后(按退格键或删除后)缩小框的大小

function updateSize(e) {
  let text = e.target.value + String.fromCharCode(event.keyCode);
  e.target.rows = text.split(/\r\n|\r|\n/).length;
}

function keyDownUpdateSize(e) {
  if (event.keyCode != 8 && event.keyCode != 46)
    updateSize(e);
}

function keyUpUpdateSize(e) {
  if (event.keyCode == 8 || event.keyCode == 46)
    updateSize(e);
}

    
  
document.querySelector(selector_to_your_textarea).addEventListener("keydown", keyDownUpdateSize);
document.querySelector(selector_to_your_textarea).addEventListener("keyup", keyUpUpdateSize);

I was looking for pure js solution (no jquery in projects) and end-up writing own solution. It is very fast, no compatibility issues and requires no extra libs.

One detail to take care about is that you need to size up box before new character appears, but size down the box after character disappears (after hitting backspace or delete)

function updateSize(e) {
  let text = e.target.value + String.fromCharCode(event.keyCode);
  e.target.rows = text.split(/\r\n|\r|\n/).length;
}

function keyDownUpdateSize(e) {
  if (event.keyCode != 8 && event.keyCode != 46)
    updateSize(e);
}

function keyUpUpdateSize(e) {
  if (event.keyCode == 8 || event.keyCode == 46)
    updateSize(e);
}

    
  
document.querySelector(selector_to_your_textarea).addEventListener("keydown", keyDownUpdateSize);
document.querySelector(selector_to_your_textarea).addEventListener("keyup", keyUpUpdateSize);

给妤﹃绝世温柔 2024-10-24 03:44:32

老问题,但你可以这样做:

html:

<textarea class="text-area" rows="1"></textarea>

jquery:

var baseH; // base scroll height

$('body')
    .one('focus.textarea', '.text-area', function(e) {
        baseH = this.scrollHeight;
    })
    .on('input.textarea', '.text-area', function(e) {
        if(baseH < this.scrollHeight) {
            $(this).height(0).height(this.scrollHeight);
        }
        else {
            $(this).height(0).height(baseH);
        }
    });

这样自动调整大小将应用于任何具有“text-area”类的文本区域。当文本被删除时也会缩小。

jsfiddle:

https://jsfiddle.net/rotaercz/46rhcqyn/

Old question but you could do something like this:

html:

<textarea class="text-area" rows="1"></textarea>

jquery:

var baseH; // base scroll height

$('body')
    .one('focus.textarea', '.text-area', function(e) {
        baseH = this.scrollHeight;
    })
    .on('input.textarea', '.text-area', function(e) {
        if(baseH < this.scrollHeight) {
            $(this).height(0).height(this.scrollHeight);
        }
        else {
            $(this).height(0).height(baseH);
        }
    });

This way the auto resize will apply to any textarea with the class "text-area". Also shrinks when text is removed.

jsfiddle:

https://jsfiddle.net/rotaercz/46rhcqyn/

慈悲佛祖 2024-10-24 03:44:32

使用 JavaScript。 textarea 的行为类似于 textarea,并且您想要更改它(您希望它的行为类似于 div),因此您必须修改您想要的行为。

这是我几个月前在某处找到的解决方案,但无法再次找到。它可能添加了我自己的风格:

标记:

<div>
  <textarea class='my-textarea' />
  <div className='my-textarea autogrow' style="display: 'none';" />
</div>

样式:

.my-textarea {
  border: 1px solid #bbb;
  font-family: Helvetica;
  font-size: 15px;
  overflow: hidden;
  padding: 5px;
  resize: none;
}

// Needs same styles as the textarea except overflow.
.autogrow {
  overflow: auto !important;
}

将此事件监听器获取到文本区域的 change 事件:

function growTextarea(e) {
  const { value } = e.target
  const textarea = e.target
  const { grower } = this

  grower.style.display = 'block'
  grower.innerHTML = value.length ? value : 'x'
  textarea.style.height = grower.offsetHeight + 'px'
  grower.style.display = 'none'
}

它是如何工作的?基本上,div 的扩展就是您希望文本区域扩展的行为。因此,您要创建一个与文本区域具有相同样式的 div,并将文本区域的值放入该 div 中。然后获取 div 的高度并将文本区域的高度设置为该高度。

使用 display none 和 block,div 会出现和消失,以便您可以测量其高度。您永远不会在浏览器中真正看到它。

希望这对你有用!

PS 我使用 React,所以我必须将我的解决方案更改为与框架无关。因此它可能存在错误或语法错误。例如,您可能需要查询文档才能找到种植者 div。

Use Javascript. textarea behaves like a textarea, and you want to change that (you want it to behave like a div), so you have to hack in the behavior you want.

Here's a solution I found somewhere a few months ago but have not been able to find again. It may have my own flavor added in:

Markup:

<div>
  <textarea class='my-textarea' />
  <div className='my-textarea autogrow' style="display: 'none';" />
</div>

Styles:

.my-textarea {
  border: 1px solid #bbb;
  font-family: Helvetica;
  font-size: 15px;
  overflow: hidden;
  padding: 5px;
  resize: none;
}

// Needs same styles as the textarea except overflow.
.autogrow {
  overflow: auto !important;
}

Get this event listener onto the textarea's change event:

function growTextarea(e) {
  const { value } = e.target
  const textarea = e.target
  const { grower } = this

  grower.style.display = 'block'
  grower.innerHTML = value.length ? value : 'x'
  textarea.style.height = grower.offsetHeight + 'px'
  grower.style.display = 'none'
}

How does it work? Basically a div's expansion is what you want the textarea's expansion to behave like. So you're making a div with all the same styles as the textarea and putting the textarea's value into the div. Then you get the div's height and set the textarea's height to that.

Using display none and block, the div appears and disappears so you can measure its height. You'll never actually see it in the browser.

Hope this works for you!

P.S. I use React so I had to change my solution to be framework agnostic. So it may have bugs or syntax errors. E.g. you might have to query the document to find the grower div.

灯角 2024-10-24 03:44:32

如果您使用 Angular2/4,那么这里有一个很棒的指令

请参阅将数据动态加载到文本区域时的问题列表以获取解决方法。除此之外,它可以与 ReactiveForms 和模板表单配合使用。

作为参考,这是指令代码:

import { Input, AfterViewInit, ElementRef, HostListener, Directive} from '@angular/core';

@Directive({
    selector: 'textarea[autosize]'
})

export class Autosize implements AfterViewInit {

    private el: HTMLElement;
    private _minHeight: string;
    private _maxHeight: string;
    private _lastHeight: number;
    private _clientWidth: number;

    @Input('minHeight')
    get minHeight() { 
      return this._minHeight;
    }
    set minHeight(val: string) {
      this._minHeight = val;
      this.updateMinHeight();
    }

    @Input('maxHeight')
    get maxHeight() {
      return this._maxHeight; 
    }
    set maxHeight(val: string) {
      this._maxHeight = val;
      this.updateMaxHeight();
    }

 @HostListener('window:resize', ['$event.target'])
    onResize(textArea: HTMLTextAreaElement) {
      //Only apply adjustment if element width had changed.
      if (this.el.clientWidth === this._clientWidth) return;
      this._clientWidth = this.element.nativeElement.clientWidth;
      this.adjust();
    }

 @HostListener('input',['$event.target'])
  onInput(textArea: HTMLTextAreaElement): void {
    this.adjust();  
  }

  constructor(public element: ElementRef){
    this.el = element.nativeElement;
    this._clientWidth = this.el.clientWidth;
  }

  ngAfterViewInit(): void{
    // set element resize allowed manually by user
    const style = window.getComputedStyle(this.el, null);
    if (style.resize === 'both') {
            this.el.style.resize = 'horizontal';
        }
    else if (style.resize === 'vertical') {
            this.el.style.resize = 'none';
    }
    // run first adjust
    this.adjust();
  }

  adjust(): void{
    // perform height adjustments after input changes, if height is different
    if (this.el.style.height == this.element.nativeElement.scrollHeight + "px") return;
    this.el.style.overflowX = 'hidden';
    this.el.style.height = 'auto';
    this.el.style.height = this.el.scrollHeight + "px";
  }

  updateMinHeight(): void{
    // Set textarea min height if input defined
    this.el.style.minHeight = this._minHeight + 'px';
  }

  updateMaxHeight(): void{
    // Set textarea max height if input defined
    this.el.style.maxHeight = this._maxHeight + 'px';
  }

}

If you are using Angular2/4 there is a great directive here that works.

See the issues list for when you are loading data dynamically into the textarea for a workaround. Other than that issue it works fine with ReactiveForms and Template forms.

For reference, this is the directive code:

import { Input, AfterViewInit, ElementRef, HostListener, Directive} from '@angular/core';

@Directive({
    selector: 'textarea[autosize]'
})

export class Autosize implements AfterViewInit {

    private el: HTMLElement;
    private _minHeight: string;
    private _maxHeight: string;
    private _lastHeight: number;
    private _clientWidth: number;

    @Input('minHeight')
    get minHeight() { 
      return this._minHeight;
    }
    set minHeight(val: string) {
      this._minHeight = val;
      this.updateMinHeight();
    }

    @Input('maxHeight')
    get maxHeight() {
      return this._maxHeight; 
    }
    set maxHeight(val: string) {
      this._maxHeight = val;
      this.updateMaxHeight();
    }

 @HostListener('window:resize', ['$event.target'])
    onResize(textArea: HTMLTextAreaElement) {
      //Only apply adjustment if element width had changed.
      if (this.el.clientWidth === this._clientWidth) return;
      this._clientWidth = this.element.nativeElement.clientWidth;
      this.adjust();
    }

 @HostListener('input',['$event.target'])
  onInput(textArea: HTMLTextAreaElement): void {
    this.adjust();  
  }

  constructor(public element: ElementRef){
    this.el = element.nativeElement;
    this._clientWidth = this.el.clientWidth;
  }

  ngAfterViewInit(): void{
    // set element resize allowed manually by user
    const style = window.getComputedStyle(this.el, null);
    if (style.resize === 'both') {
            this.el.style.resize = 'horizontal';
        }
    else if (style.resize === 'vertical') {
            this.el.style.resize = 'none';
    }
    // run first adjust
    this.adjust();
  }

  adjust(): void{
    // perform height adjustments after input changes, if height is different
    if (this.el.style.height == this.element.nativeElement.scrollHeight + "px") return;
    this.el.style.overflowX = 'hidden';
    this.el.style.height = 'auto';
    this.el.style.height = this.el.scrollHeight + "px";
  }

  updateMinHeight(): void{
    // Set textarea min height if input defined
    this.el.style.minHeight = this._minHeight + 'px';
  }

  updateMaxHeight(): void{
    // Set textarea max height if input defined
    this.el.style.maxHeight = this._maxHeight + 'px';
  }

}
心房的律动 2024-10-24 03:44:32
function autoExpand(field) {

    // Reset field height
    field.style.height = 'inherit';

    // Get the computed styles for the element
    var computed = window.getComputedStyle(field);

    // Calculate the height
    var height = parseInt(computed.getPropertyValue('border-top-width'), 10)
                 + parseInt(computed.getPropertyValue('padding-top'), 10)
                 + field.scrollHeight
                 + parseInt(computed.getPropertyValue('padding-bottom'), 10)
                 + parseInt(computed.getPropertyValue('border-bottom-width'), 10);

    field.style.height = height + 'px';

};

对我有用

https:// gomakethings.com/automatically-expand-a-textarea-as-the-user-types-using-vanilla-javascript/

function autoExpand(field) {

    // Reset field height
    field.style.height = 'inherit';

    // Get the computed styles for the element
    var computed = window.getComputedStyle(field);

    // Calculate the height
    var height = parseInt(computed.getPropertyValue('border-top-width'), 10)
                 + parseInt(computed.getPropertyValue('padding-top'), 10)
                 + field.scrollHeight
                 + parseInt(computed.getPropertyValue('padding-bottom'), 10)
                 + parseInt(computed.getPropertyValue('border-bottom-width'), 10);

    field.style.height = height + 'px';

};

Works for me

https://gomakethings.com/automatically-expand-a-textarea-as-the-user-types-using-vanilla-javascript/

多情癖 2024-10-24 03:44:32
var textarea = document.querySelector('textarea');
textarea.addEventListener('keydown', autosize);             
function autosize(){
  var el = this;
  setTimeout(function(){
    el.style.cssText = 'height:auto; padding:0';    
    el.style.cssText = 'height:' + el.scrollHeight + 'px';
  },0);
}
textarea{   
  overflow:hidden; 
  padding:10px;
  width:250px;
  font-size:14px;
  margin:50px auto;
  display:block;
  border-radius:10px;
  border:6px solid #556677;
}
<textarea rows="6" >
CSS Textarea that expands as you type text
rows Specifies the visible number of lines in a text area and cols	Specifies the visible width of a text area
</textarea>

var textarea = document.querySelector('textarea');
textarea.addEventListener('keydown', autosize);             
function autosize(){
  var el = this;
  setTimeout(function(){
    el.style.cssText = 'height:auto; padding:0';    
    el.style.cssText = 'height:' + el.scrollHeight + 'px';
  },0);
}
textarea{   
  overflow:hidden; 
  padding:10px;
  width:250px;
  font-size:14px;
  margin:50px auto;
  display:block;
  border-radius:10px;
  border:6px solid #556677;
}
<textarea rows="6" >
CSS Textarea that expands as you type text
rows Specifies the visible number of lines in a text area and cols	Specifies the visible width of a text area
</textarea>

梦纸 2024-10-24 03:44:32

这对我有用

$(".textarea").on("keyup input", function(){
    $(this).css('height', 'auto').css('height', this.scrollHeight+(this.offsetHeight - 
    this.clientHeight));
 });

this worked for me

$(".textarea").on("keyup input", function(){
    $(this).css('height', 'auto').css('height', this.scrollHeight+(this.offsetHeight - 
    this.clientHeight));
 });
盗梦空间 2024-10-24 03:44:32

为 React Angular 或 Vue 提出了简单的解决方案。

您只需将 textarea 包装在 div 中,将 textarea 的内容写入 div 中,并给出textarea 绝对位置,高度和宽度 100%(不要忘记 div 上的相对位置)。

所以现在 divtextarea 完美叠加,当 div 由于里面的文本而扩展时,textarea code> 将自动执行此操作。

不要忘记设置完全相同的填充、字体大小和字体系列。

came up with simple solution for React Angular or Vue.

You just need to wrap the textarea in a div, write the content of textarea in the div and give the textarea absolute position, height and width 100% (don't forget relative position on the div).

So now the div and the textarea are perfectly superimposed, and when the div is expanding because of the text inside, textarea will automatically do so.

Don't forget to set exact same padding, font-size and font-family.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文