关于javascript:自动扩展文本区域

Auto-expanding textarea

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

1
2
3
textarea.onkeyup = function () {
  textarea.style.height = textarea.clientHeight + 'px';
}

但是当您键入文本时,文本区域只会无限期地增长...

我知道有Dojo和一个jQuery插件,但宁愿不必使用它们。 我看了看它们的实现,最初使用的是scrollHeight,但这样做是一样的。

您可以开始接听并使用文本区域播放答案。


在使用scrollHeight正确扩展/缩小文本区域之前,请重新设置高度。 Math.min()可用于设置文本区域的高度限制。

码:

1
2
3
4
5
6
7
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";
};

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

注意:IE8和更早版本不支持input事件。如果还要支持此古老的浏览器,请将keydownkeyuponpaste和/或oncut一起使用。


我想让自动扩展区域受行数限制(例如5行)。我已经考虑过使用" em"单位,但是对于Rob的解决方案,这容易出错,并且不会考虑填充等内容。

这就是我想出的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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);
};

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


对于那些对jQuery版本的Rob W解决方案感兴趣的人:

1
2
3
4
5
var textarea = jQuery('.textarea');
textarea.on("input", function () {
    jQuery(this).css("height",""); //reset the height
    jQuery(this).css("height", Math.min(jQuery(this).prop('scrollHeight'), 200) +"px");
});


...如果您需要无限扩展的文本区域(就像我一样),请执行以下操作:

1
2
3
4
5
6
var textarea = document.getElementById("textarea");

textarea.oninput = function() {
  textarea.style.height =""; /* Reset the height*/
  textarea.style.height = textarea.scrollHeight +"px";
};

使用

可能也做同样的工作,自我扩展,不需要js