我正在尝试做一个简单的自动扩展文本区域。这是我的代码:
textarea.onkeyup = function () {
textarea.style.height = textarea.clientHeight + 'px';
}
但是文本区域会随着您的输入而无限增长...
我知道有 Dojo 和 jQuery 插件可以实现此目的,但我不想使用它们。我查看了他们的实现,最初使用 scrollHeight 但做了同样的事情。
您可以开始回答并使用文本区域来播放您的答案。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我希望自动扩展区域受行数限制(例如 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); };小提琴:http://jsfiddle.net/cgSj3/
在使用
scrollHeight正确扩展/收缩文本区域之前重置高度。Math.min()可用于设置文本区域高度的限制。代码:
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
注意:
input事件IE8 及更早版本不支持 。如果您也想支持这个古老的浏览器,请使用keydown或keyup以及onpaste和/或oncut。