DIV CSS 佈局教程網

用 jQuery 讓 textarea 隨內容自適應高度
編輯:關於JavaScript     

瀏覽器默認的 textarea 高度固定,內容一多就出現內部滾動條,輸入體驗不太好。理想的行為是:內容增加時高度跟著長,直到達到上限才出現滾動條。下面這個插件封裝兼容性不錯,可以直接複用。

實現原理

核心只有一步:先把高度臨時設為 0,讀取 scrollHeight 拿到內容真實高度,再夾在最小與最大值之間重新設置。設為 0 是為了避免「只增不减」——否則刪除內容後高度不會回落。

觸發時機綁定 keyup、change、focus 三個事件,覆蓋鍵盤輸入、程序賦值和粘貼等情況。

完整代碼

<body>
<textarea id="textarea1"></textarea>
<textarea id="textarea2"></textarea>
<textarea id="textarea3" style="overflow-y:hidden; height:20px; resize: none"></textarea>

<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function () {
    // 使用默認的最小與最大高度
    $("#textarea1").textareaAutoHeight();
    // 最大高度為 100px
    $("#textarea2").textareaAutoHeight({ maxHeight: 100 });
    // 最小 50px,最大 200px
    $("#textarea3").textareaAutoHeight({ minHeight: 50, maxHeight: 200 });
});

$.fn.extend({
    textareaAutoHeight: function (options) {
        this._options = {
            minHeight: 0,
            maxHeight: 1000
        };

        this.init = function () {
            for (var p in options) {
                this._options[p] = options[p];
            }
            // 未指定最小高度時,以元素當前高度為基準
            if (this._options.minHeight == 0) {
                this._options.minHeight = parseFloat($(this).height());
            }
            for (var p in this._options) {
                if ($(this).attr(p) == null) {
                    $(this).attr(p, this._options[p]);
                }
            }
            $(this).keyup(this.resetHeight)
                   .change(this.resetHeight)
                   .focus(this.resetHeight);
        };

        this.resetHeight = function () {
            var _minHeight = parseFloat($(this).attr("minHeight"));
            var _maxHeight = parseFloat($(this).attr("maxHeight"));

            if (!$.browser.msie) {
                $(this).height(0); // 先歸零,才能拿到準確的 scrollHeight
            }

            var h = parseFloat(this.scrollHeight);
            h = h < _minHeight ? _minHeight : (h > _maxHeight ? _maxHeight : h);
            $(this).height(h).scrollTop(h);

            if (h >= _maxHeight) {
                $(this).css("overflow-y", "scroll");
            } else {
                $(this).css("overflow-y", "hidden");
            }
        };

        this.init();
    }
});
</script>
</body>

使用與定制度說明

調用時只需傳入 minHeight 和 maxHeight 兩個可選參數。不傳 minHeight 時,插件會以 textarea 自身的初始高度作為下限,這樣可以通過 CSS 控制默認行高,而不必在 JS 裡寫死。

達到 maxHeight 後會自動把 overflow-y 切換為 scroll,此時行為就退化回原生 textarea,符合用戶預期。

需要注意的地方

$.browser 已被移除。這個判斷在 jQuery 1.9 之後不再可用,新項目請改用 navigator.userAgent 檢測,或直接去掉——歸零操作在現代瀏覽器中都是安全的。

用 keyup 會漏掉部分場景。中文輸入法在選字過程中 keyup 觸發的順序與預期不同,可能導致高度更新不及時。更穩妥的做法是同時監聽 input 事件,它能覆蓋輸入法確認、粘貼、自動填充等所有情況。

用 attr 存配置並非好主意。把 minHeight、maxHeight 掛在 DOM 屬性上,是為了在 resetHeight 內能拿到配置。更規範的寫法是把配置保存在閉包變量裡,避免污染 DOM。

如果不需要兼容老舊瀏覽器,其實現在有更簡短的方案:純 CSS 的 field-sizing: content,或監聽 input 後直接 this.style.height = this.scrollHeight + 'px',幾行代碼就能搞定。這個插件的價值在於示範了「插件封裝 + 可配置上下限 + 滾動條自動切換」這套完整思路。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved