textarea高度隨文本內容變化,且不出現滾動條


通常文本域的寫法如下

<textarea type="text" class="form-control pull-left" id="description" name="description"></textarea>

在頁面的顯示效果如下

一般會有一個初始高度,當不對該文本域進行處理,文本域的高度不會發生變化,當文本域內的內容過多時,將會出現滾動條,效果如下

效果不美觀。

現在想讓文本域的高度隨內容的多少而發生改變,且不會產生滾動條。

可以使用以下代碼

$('textarea').each(function () {
        this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
    }).on('input', function () {
        this.style.height = 'auto';
        this.style.height = (this.scrollHeight) + 'px';
    });

顯示效果如下

該文本域的高度會隨着內容的增多而變大,也會隨着內容的減少而減小。實時變化。

 

有時候情況會比較復雜,例如我在做一個項目,前台使用的是bootstrap,使用model模態框彈出一個頁面,在頁面上有一個文本域,保持原本的代碼保持不變,效果就發生了變化。

我猜想這種效果的出現可能是因為彈出框的高度和寬度問題。

后來改了一下代碼,首先給文本域一個默認高度

<textarea type="text" class="form-control pull-left" id="description" name="description" style="height: 50px"></textarea>

文本域得到焦點后,再實時監控文本域里的內容,然后讓高度隨之變化。

$("#description").focus(function () {
        $('textarea').each(function () {
            this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
        }).on('input', function () {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
        });
    });

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM