前言
這是一個很普遍的體驗, 而且實現起來也很簡單哦
參考
YouTube – How to Auto Resize Textarea using HTML CSS & JavaScript
效果
我故意加了 border 和 padding 來解釋.
Step by Step 實現
HTML
<textarea class="stg-text-area-autoresize" rows="4"></textarea>
CSS Style
textarea { font-size: 1.5rem; padding-inline: 1rem; background-color: pink; border-inline: unset; outline: unset; // 我刻意加入 border padding 來讓情況變得複雜 padding-top: 15px; padding-bottom: 20px; border-top: 15px solid red; border-bottom: 20px solid red; }
效果
JavaScript
const textarea = document.querySelector('textarea'); // 監聽, 每一次 input 的時候看需不需要 resize textarea.addEventListener('input', () => { // 先把 height 設置成 auto, 這樣就可以還原小 textarea.style.height = 'auto'; // 獲取當前的 border block const { borderTopWidth, borderBottomWidth } = window.getComputedStyle(textarea); // 在把 height 設置成 scrollHeight 讓它變大 // 之所以需要加 border 是因爲 height 在 border-box 情況下是要包括 border 高度的. // 而 scrollHeight 只有到 padding 的高度 textarea.style.height = `${ textarea.scrollHeight + parseFloat(borderTopWidth) + parseFloat(borderBottomWidth) }px`; });
關鍵就在改變 textare height
auto 變小
scrollHeight 變大
如果想了解 height, scrollHeight 是如何計算的, 可以看這篇: DOM – Dimension (offset, client, computed, rect)