Home > Article > Web Front-end > Non-mainstream textarea self-growth implementation js code_javascript skills
Most of them are accomplished by scrollHeight (non-W3C standard, introduced by IE) and keyup events. One of the more interesting ones is implemented through "mirror element" and setTimeout polling. The general implementation idea is as follows:
Position a separate pre element outside the client view through position:absolute, and set it to the same style as the textarea. We call this pre element "mirror", and then perform 200ms polling through setTimeout to update the new value in the textarea to the mirror element. Since the mirror element is set to block, its size will change with the amount of content, and then obtain the mirror element The offsetHeight is applied to the corresponding textarea so that its height changes with the content.
This is indeed a good idea. However, such polling seems a bit "wasteful", because the average user will not keep inputting, and it is more resource-intensive to calculate the offsetHeight every time.
Now that we have discovered the problem, we will improve it and make modifications based on other people’s ideas. It will not be too difficult.
First remove the operation of calculating the offsetHeight of the mirror element. We can use a wrapper to wrap the mirror element and the textarea, and set their styles to be the same. The mirror element is hidden through visibility:hidden (note that it is not display:none) , so that the mirror element space is still occupied, then position the textarea absolutely relative to the wrapper, and cover the textarea on the mirror element. In our example, the textarea covers the pre, and the height and width attributes of the textarea are set to 100%. , so that the height change of pre can be directly reflected on the wrapper, and the size of textarea will also change accordingly. This is all automatic. We have taken advantage of the characteristics of "block-level" elements
for endless polling , I still think using keyup is better, but in terms of event processing, we can give the user a time interval, and do not need to process every input. The time interval set in the example is 250ms. When the user inputs, , if the user pauses and there is a 250ms gap, assign the value of textarea to the span of pre.
Now that the idea has been explained, it should be relatively simple.
The following is the html and corresponding javascript (I have fallen in love with mootools recently). Since the css is long, you can see the jsfiddle share at the bottom of the page for details.