[英]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(元素列表)。
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]
。 它可能在大多數時間都有效,但是當該類在頁面上多次存在時,可能會導致意外情況。 document.getElementById()
。 我不知道您是否絕對要出於學習或其他原因自己編碼:-)
無論如何,如果您願意使用現有的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.