Creating a TextArea with Auto-Resize that Shrinks
Challenge: Previous attempts to create a textarea with auto-resize failed to shrink the textarea upon content deletion.
Solution:
The provided code from the original thread adjusts the height of the textarea based on its content. However, it does not account for content deletion, resulting in an incorrect clientHeight value.
To overcome this limitation, a more comprehensive solution is needed:
function FitToContentWithShrink(id, maxHeight) { var text = id && id.style ? id : document.getElementById(id); if (!text) return; var newHeight = text.scrollHeight; var currentHeight = text.clientHeight; // Check if the content has changed if (newHeight !== currentHeight) { if (newHeight > currentHeight) { // If the new height is greater than the current height, expand text.style.height = newHeight + "px"; } else if (newHeight < currentHeight) { // If the new height is less than the current height, shrink text.style.height = newHeight + "px"; } } }
Benefits:
Usage:
window.onload = function () { document.getElementById("ta").onkeyup = function () { FitToContentWithShrink(this, 500); }; };
Additional Note:
Applying JavaScript in strict mode will not affect the functionality of this solution.
The above is the detailed content of How to Create a Self-Resizing TextArea That Shrinks on Content Deletion?. For more information, please follow other related articles on the PHP Chinese website!