本來textarea只有一行高,隨着輸入字數的增多,默認增加,一般會用在移動端產品輸入上spa
使用oninput比onkeyup更適合手機端code
<textarea id="txtContent" class="j_comment_in comment-input" rows="1" oninput="ResizeTextarea('txtContent')" style="overflow-y:hidden;" placeholder="我也說一句..."></textarea>
//最小高度 var minRows = 1; // 最大高度,超過則出現滾動條 var maxRows = 6; function ResizeTextarea(id){ var t = document.getElementById(id); if (t.scrollTop == 0) t.scrollTop=1; while (t.scrollTop == 0){ if (t.rows > minRows) t.rows--; else break; t.scrollTop = 1; if (t.rows < maxRows) t.style.overflowY = "hidden"; if (t.scrollTop > 0){ t.rows++; break; } } while(t.scrollTop > 0){ if (t.rows < maxRows){ t.rows++; if (t.scrollTop == 0) t.scrollTop=1; } else{ t.style.overflowY = "auto"; break; } } }
js監聽的寫法blog
document.getElementById("txtContent").addEventListener("input", ResizeTextarea, false);