功能特性
- 輸入換行(Enter)時自動增加一行高度。
- 刪除換行(Backspace/Delete)時自動減少一行高度。
- 無需額外 CSS、無依賴、極簡調用。
插件核心代碼
jQuery.extend({
textareaAutosize: function() {
$("textarea[data-autosize]").on("input propertychange", function() {
var $ta = $(this);
// 保存原始樣式,避免干擾
var lineHeight = parseInt($ta.css("line-height")) || 20;
var minHeight = parseInt($ta.css("min-height")) || lineHeight;
// 關鍵:scrollHeight 包含內容實際高度(含 padding)
var scrollH = this.scrollHeight;
// 重置高度為 auto 獲取真實 scrollHeight,再設置
$ta.css('height', 'auto');
var newHeight = Math.max(this.scrollHeight, minHeight);
$ta.css('height', newHeight + 'px');
});
}
});
// 一鍵啟用所有帶 [data-autosize] 的 textarea
$.textareaAutosize();
HTML 使用
<textarea class="form-control" data-autosize
style="min-height:60px; line-height:20px; resize:none;"
placeholder="請輸入內容..."></textarea>
原理解析
- 監聽
input 事件(現代)+ propertychange(IE8- 兼容)。
- 臨時將
height: auto 讓瀏覽器計算內容真實高度(scrollHeight)。
- 設置
height = max(scrollHeight, minHeight) 實現自適應。
resize: none 禁用瀏覽器自帶拖拽手柄,避免衝突。
對比原文方案的改進
| 原文方案 | 改進版 |
| 基於換行符計數估算行高 | 直接用 scrollHeight 精確獲取渲染高度 |
需手動維護 enterCount 屬性 | 無狀態,自動適應粘貼、剪切、撤銷等操作 |
| 不支持 min-height/max-height | 完美支持 CSS min/max-height 限制 |
| line-height 像素解析脆弱 | 不依賴 line-height,自動適應字體大小變化 |
擴展:限制最大高度並顯示滾動條
textarea[data-autosize] {
max-height: 200px; /* 超過顯示滾動條 */
overflow-y: hidden; /* 自適應時隱藏滾動條 */
}
textarea[data-autosize].overflow {
overflow-y: auto; /* JS 中超過 max-height 時添加此類 */
}