I. Background introduction

In an old project, you need to use to texarea components, long and large project, the default texarea style, and you won’t come after a search, and did not find the style not to reason, ability and the time is limited, decided to separate to texarea writing style and highly adaptive (i.e. not a scrollbar, height change with content)

Second, style Settings

I won’t say much about styles, but go straight to the code (use the Textarea style from Element-UI)

{ min-height: 54px; height: 54px; display: block; resize: vertical; padding: 5px 15px; The line - height: 1.5; box-sizing: border-box; width: 100%; font-size: inherit; color: #606266; background-color: #fff; background-image: none; border: 1px solid #dcdfe6; border-radius: 4px; The transition: border - color. 2 s cubic bezier - (. 645,. 045,. 355, 1); }Copy the code

Third, highly adaptive thinking

Several steps to achieve adaptive height

  1. Listening to thetextareaContent change
  2. After the calculation content changestextareaThe height of the
  3. totextareaSet a new height

Fourth, concrete implementation

Now that I have an idea, let’s implement it one by one

  1. Monitor content change

    / / get the textarea const textarea = document. GetElementById (' myTextarea ') / / listening contents change textarea. AddEventListener (' input ', function(e) { })Copy the code

2. Calculate the height of the textarea after the content changes

Box-sizing for textarea is set to border-box, so the height should be the height of the content + the height of the border above and below

/ / to monitor content change textarea. AddEventListener (' input ', Function (e) {const scrollHeight = textarea const scrollHeight = textarea Since the textarea border may have a higher level of style defined elsewhere // The style read using getComputedStyle is the final style, Including the inline style, embedded style and external style. / / the document defaultView. GetComputedStyle element (element [, pseudo -]); // or // window.getcomputedStyle (element[,pseudo-element]); const style = getComputedStyle(textarea) const borderTop = parseInt(s.borderTopWidth) const borderBottom = parseInt(s.borderBottomWidth) const height = scrollHeight + borderTop + borderBottom })Copy the code

3. Set a new height for the Textarea

    textarea.style.height = height + 'px'
Copy the code

4. Run code tests

Conform to expected effect

Four,

Record the problems encountered in the process of their own development, convenient for their own later view, also hope to encounter the same problem partners can do a reference, there are insufficient places, please kindly comment, thank you

In our development process, there will always be problems of one kind or another. It is not terrible to encounter problems. As long as you face them and find solutions, I believe you will learn more knowledge