如何用原生JavaScript动态调整textarea的行数?
Fixing the Dynamic Textarea Resize Function
Hey there, let's get that do_resize function working perfectly so your textarea automatically adjusts its height based on the content inside it. Here's the completed, polished version along with breakdowns of how it works:
Complete Working Function
function do_resize(textbox) { var maxrows = 50; var txt = textbox.value; var cols = textbox.cols; var arraytxt = txt.split('\n'); var rows = arraytxt.length; // Calculate extra rows for lines that wrap past the column limit for (var i = 0; i < arraytxt.length; i++) { const lineLength = arraytxt[i].length; if (lineLength === 0) continue; // Skip empty lines to avoid false calculations // Add rows for wrapped content rows += Math.floor(lineLength / cols); // Adjust for exact multiples (e.g., 150 chars in 150 cols doesn't need an extra row) if (lineLength % cols === 0) { rows -= 1; } } // Keep rows within our defined bounds rows = Math.min(rows, maxrows); // Don't go over the max allowed rows // Optional: Don't shrink below the initial row count (adjust as needed) const initialRows = parseInt(textbox.getAttribute('rows')) || 1; rows = Math.max(rows, initialRows); // Update the textarea's row count textbox.rows = rows; }
Key Improvements & Explanations
- Wrapped Line Calculation: The original code started counting extra rows for long lines, but missed a critical edge case: when a line's length is exactly a multiple of
cols(like 150 characters in a 150-col textarea). We fix that by subtracting 1 row in those cases, since the text fits perfectly without an extra line break. - Bounds Checking: We ensure the row count never exceeds your
maxrowslimit, and optionally keep it from shrinking below the textarea's initial row count (so it doesn't collapse to a tiny box if content is deleted). - Empty Line Handling: We skip empty lines to avoid unnecessary calculations that could throw off the row count.
Quick Usage Tweaks
For a better user experience, change the trigger event from onClick to onInput—this way the resize happens automatically as the user types or pastes content, not just when they click the textarea:
<textarea class="form-control" onInput="do_resize(this)" rows="10" cols="150" id="textvalue" style="margin-top: 0px; margin-bottom: 0px;">some text </textarea>
Also, consider removing the fixed height style property—let the rows attribute control the height instead for more consistent behavior across browsers.
内容的提问来源于stack exchange,提问作者Andrey Radkevich
相关产品推荐
相关产品推荐

