自动扩展textarea [英] Auto-expanding textarea
问题描述
我正在尝试做一个简单的自动扩展textarea。这是我的代码:
I'm trying to do a simple auto-expanding textarea. This is my code:
textarea.onkeyup = function () {
textarea.style.height = textarea.clientHeight + 'px';
}
但是当你输入时,textarea会无限增长......
But the textarea just keeps growing indefinitely as you type...
我知道有Dojo和jQuery插件,但不想使用它们。我查看了他们的实现,并且最初使用 scrollHeight
,但这也做了同样的事情。
I know there is Dojo and a jQuery plugin for this, but would rather not have to use them. I looked at their implementation, and was initially using scrollHeight
but that did the same thing.
您可以开始回答并使用textarea来回答您的问题。
You can start answering and play with the textarea for your answer to play with.
推荐答案
在使用 scrollHeight
扩展/缩小textarea之前重置高度正确。 Math.min()
可用于设置textarea高度的限制。
Reset the height before Using scrollHeight
to expand/shrink the textarea correctly. Math.min()
can be used to set a limit on the textarea's height.
代码:
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
Fiddle: http://jsfiddle.net/gjqWy/155
注意: 输入
事件不是IE8及更早版本支持。使用 keydown
或 keyup
使用 onpaste
和/或 oncut
如果你想支持这个古老的浏览器。
Note: The input
event is not supported by IE8 and earlier. Use keydown
or keyup
with onpaste
and/or oncut
if you want to support this ancient browser as well.
这篇关于自动扩展textarea的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!