Automatically expand text area
P粉245489391
P粉245489391 2023-10-21 08:49:23
0
2
510

I'm trying to make a simple auto-expanding text area. This is my code:

textarea.onkeyup = function () { textarea.style.height = textarea.clientHeight + 'px'; }

But the text area will grow infinitely as you type...

I know there are Dojo and jQuery plugins for this, but I don't want to use them. I looked at their implementation and originally usedscrollHeightbut did the same thing.

You can start answering and use the text area to play your answer.

P粉245489391
P粉245489391

reply all (2)
P粉786800174

I want the auto-expand area to be limited by the number of rows (e.g. 5 rows). I considered using "em" units, forRob's solution, however, this iserror-proneand doesn't take into account stuff like padding.

This is my idea:

var textarea = document.getElementById("textarea"); var limitRows = 5; var messageLastScrollHeight = textarea.scrollHeight; textarea.oninput = function() { var rows = parseInt(textarea.getAttribute("rows")); // If we don't decrease the amount of rows, the scrollHeight would show the scrollHeight for all the rows // even if there is no text. textarea.setAttribute("rows", "1"); if (rows < limitRows && textarea.scrollHeight > messageLastScrollHeight) { rows++; } else if (rows > 1 && textarea.scrollHeight < messageLastScrollHeight) { rows--; } messageLastScrollHeight = textarea.scrollHeight; textarea.setAttribute("rows", rows); };

Fiddle:http://jsfiddle.net/cgSj3/

    P粉447785031

    Reset the height before correctly expanding/shrinking the text area usingscrollHeight.Math.min()Can be used to set the height limit of the text area.

    Code:

    var textarea = document.getElementById("textarea"); var heightLimit = 200; /* Maximum height: 200px */ textarea.oninput = function() { textarea.style.height = ""; /* Reset the height*/ textarea.style.height = Math.min(textarea.scrollHeight, heightLimit) + "px"; };

    Fiddle:http://jsfiddle.net/gjqWy/155

    Note:inputevents are not supportedin IE8 and earlier. If you also want to support this ancient browser, please usekeydownorkeyupandonpasteand/oroncut.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!