簡體   English   中英

調整文本區域的大小以適應加載 jquery 時的所有文本

[英]Resize text area to fit all text on load jquery

我知道對此有很多討論,但我還沒有找到解決我的需求的解決方案。 基本上我需要在你輸入時而不是在加載時自動增長文本區域。 我正在從數據庫中提取內容並根據用戶的設置在文本區域上生成一個覆蓋層,但是這樣做時文本區域不可滾動,因此我需要自動調整這些內容以顯示所有文本。

我試過 scrollHeight 但這並不好用,因為屏幕上有多個文本框

謝謝

嘗試這個

$("textarea").height( $("textarea")[0].scrollHeight );

演示


更新

作為使其在較舊的 IE-s 中工作的技巧,只需在執行它之前添加一個非常短的延遲

window.setTimeout( function() {
    $("textarea").height( $("textarea")[0].scrollHeight );
}, 1);​

演示

多個文本區域的更新

$("textarea").each(function(textarea) {
    $(this).height( $(this)[0].scrollHeight );
});

這對我有用; 它循環遍歷頁面 Ready 上的所有“textarea”元素,並設置它們的高度。

$(function () {
    $("textarea").each(function () {
        this.style.height = (this.scrollHeight+10)+'px';
    });
});

您還可以將它與自動擴展功能結合起來,使其在編寫時也完全動態:

function autoresize(textarea) {
    textarea.style.height = '0px';     //Reset height, so that it not only grows but also shrinks
    textarea.style.height = (textarea.scrollHeight+10) + 'px';    //Set new height
}

並從“keyup”事件或通過 jQuery 調用它:

$('.autosize').keyup(function () {
    autoresize(this);
});

請注意我如何將 10px 添加到滾動高度:在這里您可以調整您希望文本區域底部為用戶提供的空間量。

希望能幫助某人。 :)

編輯:根據@Mariannes 評論更改了答案。

你可以用這個。 這個對我有用。

 $('#content').on('change keyup keydown paste cut', 'textarea', function () { $(this).height(0).height(this.scrollHeight); }).find('textarea').change();
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="content"> <textarea>How about it</textarea><br /> <textarea>111111 222222 333333 444444 555555 666666</textarea> </div>

你提到有多個文本框。 這段代碼會根據自己的內容設置每個textarea的高度。

$(document).ready( function( ) {

    $("textarea").each( function( i, el ) {
        $(el).height( el.scrollHeight );
    ​});

});

在這里擺弄

或者,您可以在 HTML 5 中使用可編輯的 div。

參考: http : //www.w3.org/TR/2011/WD-html5-20110525/editing.html#contenteditable

這是一種解決方法.. 也可能是替代解決方案:

 $('textarea').each(function(){
    var height = $('<div style="display:none; white-space:pre" id="my-hidden-div"></div>')
                 .html($(this).val())
                 .appendTo('body')
                 .height();     
   $(this).css('height',height + 'px');
   $('#my-hidden-div').remove();

});

你可以在這里看到一個演示http://jsfiddle.net/gZ2cC/

Tormod Haugene 的解決方案對我有用。

但是我的 textareas 在手風琴中,顯然它只有在 textarea 在頁面加載時可見時才有效。 手風琴項目是通過單擊具有“標題”類的元素來觸發的。

所以我修改了代碼 Tormod Haugene 以在手風琴內容中工作,這些內容設置為顯示:頁面加載時無。

在這種情況下,這可能對其他人有用:

jQuery(document).on('click', '.title', function () {
    jQuery("textarea").each(function () {
        this.style.height = (this.scrollHeight+10)+'px';
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM