自动扩展textarea

Dev*_*ode 24 javascript

我正在尝试做一个简单的自动扩展textarea.这是我的代码:

textarea.onkeyup = function () {
  textarea.style.height = textarea.clientHeight + 'px';
}
Run Code Online (Sandbox Code Playgroud)

但是当你打字时,textarea会无限增长......

我知道有Dojo和jQuery插件,但不想使用它们.我看了他们的实现,并且最初使用scrollHeight但是做了同样的事情.

您可以开始回答并使用textarea来回答您的问题.

Rob*_*b W 50

在使用之前重置高度scrollHeight以正确展开/缩小textarea.Math.min()可用于设置textarea高度的限制.

码:

var textarea = document.getElementById("textarea");
var heightLimit = 200; /* Maximum height: 200px */

textarea.oninput = function() {
  textarea.style.height = ""; /* Reset the height*/
  textarea.style.height = Math.min(textarea.scrollHeight, heightLimit) + "px";
};
Run Code Online (Sandbox Code Playgroud)

小提琴:http://jsfiddle.net/gjqWy/155

注意:IE8及更早版本不支持该input事件.使用keydownkeyup使用onpaste和/或oncut如果您想支持这个古老的浏览器.


Vit*_*lyB 8

我想让自动扩展区域受到行号(例如5行)的限制.我考虑过使用"em"单元,但对于Rob的解决方案,这很容易出错并且不会考虑填充等问题.

所以这就是我提出的:

var textarea = document.getElementById("textarea");
var limitRows = 5;
var messageLastScrollHeight = textarea.scrollHeight;

textarea.oninput = function() {
    var rows = parseInt(textarea.getAttribute("rows"));
    // If we don't decrease the amount of rows, the scrollHeight would show the scrollHeight for all the rows
    // even if there is no text.
    textarea.setAttribute("rows", "1");

    if (rows < limitRows && textarea.scrollHeight > messageLastScrollHeight) {
        rows++;
    } else if (rows > 1 && textarea.scrollHeight < messageLastScrollHeight) {
        rows--;
    }

    messageLastScrollHeight = textarea.scrollHeight;
    textarea.setAttribute("rows", rows);
};
Run Code Online (Sandbox Code Playgroud)

小提琴:http://jsfiddle.net/cgSj3/