簡體   English   中英

Javascript調整Textarea大小

[英]Javascript Resize Textarea

我試圖根據其中的文本量來調整頁面上多個textareas的大小。 通過替換周圍的標簽在事件處理程序中創建文本區域:

$('.container').on('click', '.js-post-edit-button', function (e) {
    e.preventDefault();
    const $form = $(this).parentsUntil(".js-post-update-form").parent();
    const $h5 = $form.find(".post-title");
    const $p = $form.find(".post-content");
    $h5.replaceWith($("<textarea/>", {
        "name": "post_edit[title]",
        "class": "form-control js-textarea-content",
        "id": "js-textarea-title",
        "style": "margin-bottom: 20px;",
        "text": $h5.text().replace("\n", "").replace(/\s{2,}/g, " ").trim(),
    }));
    $p.replaceWith($("<textarea/>", {
        "name": "post_edit[description]",
        "class": "form-control js-textarea-content",
        "id": "js-textarea-description",
        "style": "margin-bottom: 20px;",
        "text": $p.text().replace("\n", "").replace(/\s{2,}/g, " ").trim(),
    }));
    resizeTextarea();
});

function resizeTextarea () {
    const textarea = document.getElementsByClassName("form-control js-textarea-content");
    textarea.style.height = 'auto';
    textarea.style.height = text.scrollHeight+'px';
}

當我單擊編輯按鈕(js-post-edit-button)時,出現以下錯誤:

Uncaught TypeError: Cannot set property 'height' of undefined

誰能告訴我為什么我會收到此錯誤?

NewToJS幾乎已經給了您答案。 我會嘗試增加一些細微差別。

為什么編碼不起作用

根據MDN文檔, getElementsByClassName()返回HTMLCollection(元素列表)。

  • 您正在嘗試從此集合的另一個屬性(樣式)訪問一個屬性(高度)。 由於HTMLCollection上不存在'style'屬性,因此它將返回undefined
  • 現在,您正在嘗試更改此屬性的“高度”屬性。

那應該解釋為什么您得到錯誤:

Uncaught TypeError: Cannot set property 'height' of undefined

替代方法

我只是將函數更改為接受元素作為參數。

function resizeTextarea ( textarea ) {
    textarea.style.height = 'auto';
    textarea.style.height = text.scrollHeight+'px';
}

您還可以使用更多的OOP方法,並向HTMLTextAreaElement.prototype添加新方法。 我想無論你喜歡什么。

現在您可以根據需要獲取元素

  • 不建議使用getElementsByClassName()[0] 它可能在大多數時間都有效,但是當該類在頁面上多次存在時,可能會導致意外情況。
  • 如果您100%確保該元素在頁面上僅出現一次,則最好使用document.getElementById()
  • 在javascript中生成元素時,可以使用對該元素的引用。

我不知道您是否絕對要出於學習或其他原因自己編碼:-)

無論如何,如果您願意使用現有的js插件,我可以建議您使用這個出色的插件: http : //www.jacklmoore.com/autosize/

像這樣的單行代碼autosize($('textarea'))可以立即工作...

這是一個JsFiddle示例

 $('#autosize').autosize(); 
 <script src="https://code.jquery.com/jquery-1.11.0.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/autosize.js/1.18.4/jquery.autosize.min.js"></script> <textarea id="autosize" style="width:200px;"> First Second Third</textarea> 

暫無
暫無

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

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