Html 如何使用 CSS3 自动增长文本区域?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17731083/
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-08-29 11:18:08  来源:igfitidea点击:

How to autogrow text area with CSS3?

htmlcss

提问by Rolando

Given a textarea that starts off as a small box, single line, is it possible using CSS3 to automatically grow to have multiple lines as the user types multiple lines up until say a set limit (300px) when a scrollbar would appear with overflow auto with all the inputs?

给定一个 textarea 开始为一个小框,单行,是否有可能使用 CSS3 自动增长多行,因为用户键入多行直到设置限制(300px),当滚动条出现时自动溢出所有的输入?

采纳答案by tecshaun

Yes you can with css3. You may need to prefix these with the browser.

是的,你可以用 css3。您可能需要在浏览器中添加这些前缀。

textarea { 
    resize: both; 
} /* none|horizontal|vertical|both */
textarea.vert { 
    resize: vertical; 
}
textarea.noResize { 
    resize: none; 
}

You can then restrain them to max heights and widths using:

然后,您可以使用以下方法将它们限制在最大高度和宽度:

textarea { 
    resize: vertical; 
    max-height: 300px; 
    min-height: 200px; 
}
textarea.horiz { 
    resize: horizontal; 
    max-width: 400px; 
    min-width: 200px;
}

I've pulled these from a post I've referenced in the past:

我从我过去引用的帖子中提取了这些:

Customize Textarea Resizing with CSS

使用 CSS 自定义 Textarea 调整大小

回答by Zachary Dahan

Unfortunately, it seems that you cannot do this with only CSS3.

不幸的是,似乎仅使用 CSS3 无法做到这一点。

But, there's a 3.2k minified JS alternative to do so.

但是,有一个 3.2k 缩小的 JS 替代方案。

Here's the linkincluding demo and usage.

这是包括演示和用法的链接

You can install it by doing npm install autosizeand using this way

您可以通过这样做npm install autosize和使用这种方式来安装它

autosize(document.querySelector('.yourTextAreaClass'));

Or jQuery style

或者 jQuery 风格

autosize($('.yourTextAreaClass'));

And it works like a charm. It's lightweight and has a natural feel unlike many autoresize that are doing useless animations.

它就像一个魅力。与许多做无用动画的自动调整大小不同,它轻巧且具有自然的感觉。

回答by Adam Reis

Not possible with just CSS as far as I'm aware, but here's a super tiny Angular directive that works just by checking for new lines. You can easily adjust it to have max rows etc.

据我所知,仅使用 CSS 是不可能的,但这里有一个超小的 Angular 指令,它仅通过检查新行就可以工作。您可以轻松调整它以获得最大行数等。

angular.module('Shared.AutoGrow.Directive', [])
.directive('autoGrow', function() {
  return {
    restrict: 'A',
    link(scope, element) {
      element.on('input change', () => {
        const text = element[0].value;
        const lines = 1 + (text.match(/\n/g) || []).length;
        element[0].rows = lines;
      });
    },
  };
});

Plain JS solution should be easy to deduce, just need to apply an event listener on the element on input/change and that's it.

简单的 JS 解决方案应该很容易推断,只需要在输入/更改元素上应用一个事件监听器,就是这样。