多行輸入框最惱人的地方是高度固定:內容少時一片空白,內容多時又得在小小的框裡滾 scrollbar。autoGrow 的做法是讓 textarea 的高度跟著內容長,直到達到上限才改成內部捲動。
<script type="text/javascript" src="Scripts/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.autogrow.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#autogrow').autogrow();
});
</script>
</head>
<body>
<form action="#" method="post">
<fieldset>
<legend>auto growing textarea</legend>
<textarea id="autogrow" cols="20" rows="4">this textarea will grow indefinitely.</textarea>
</fieldset>
</form>
(function ($) {
$.fn.autogrow = function (options) {
var defaults = { minHeight: 0, maxHeight: 9999 };
var options = $.extend(defaults, options);
return this.each(function () {
var element = $(this);
var lastValLength, lastWidth; // 上次的內容長度與寬度
var valLength, width, height;
if (!element.is('textarea')) { return; }
element.css('overflow', 'hidden') // 內容超出時先隱藏捲軸
.keyup(function () {
valLength = $(this).val().length;
// jQuery 1.8 起取 CSS 屬性改用 prop
// 若使用 1.6 以下版本,請把 prop 換成 attr
width = $(this).prop('offsetWidth');
// 有刪除動作,或寬度變了(換行位置改變),先歸零重算
if (valLength < lastValLength || width != lastWidth) {
$(this).height(0);
}
// 在最小與最大高度之間,取 scrollHeight 作為合適高度
height = Math.max(options.minHeight,
Math.min($(this).prop('scrollHeight'), options.maxHeight));
// 若內容真的超過上限,才讓它出現捲軸
$(this).css('overflow', ($(this).prop('scrollHeight') > height ? 'auto' : 'hidden'))
.height(height);
lastValLength = valLength;
lastWidth = width;
});
});
};
})(jQuery);
用 scrollHeight 決定高度:textarea 的 scrollHeight 就是內容實際需要的高度,直接拿來當成新的 height,即可剛好包住內容。這比估算行數再乘行高準確得多。
縮小時要先歸零:如果只往上加,刪除文字後高度不會縮回。程式在偵測到「內容變短」或「寬度變動」時先把高度設為 0,再重新量 scrollHeight,這樣放大縮小都正確。寬度變動之所以要重算,是因為視窗縮放會改變換行位置,進而改變所需高度。
overflow 的切換時機:只有在高度已經被 maxHeight 卡住時,才把 overflow 設為 auto。反過來說,當 scrollHeight 大於目前高度,就代表內容滿溢出來了。
目前只綁定 keyup,因此用滑鼠剪貼、右鍵貼上、或輸入法候選選字造成的變動不會觸發。實戰建議改綁 input 事件(涵蓋所有內容變更),並在 change、視窗 resize 時也重算一次。另外,把 prop('offsetWidth') 與 prop('scrollHeight') 重複取值的部分抽出來,也能少幾次不必要的 DOM 讀取。
這個外掛示範的觀念很通用:先用瀏覽器提供的 scrollHeight 量出真實需求,再回寫高度,中間夾一層上下限。同样的思路也適用在無限延伸的內容卡片、聊天輸入框等場景。完整檔案可參考 jQuery.plugin.autogrow。