Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize the adaptive height of textarea

Shulou Source: shulou.com Published: 2022-06-01 11:23:15 09月26日 Update

In this article, the editor introduces "how to achieve textarea adaptive height" in detail, the content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to achieve textarea adaptive height" can help you solve your doubts.

Method

1. HTML structure:

2. CSS code:

* {padding: 0; margin: 0;} # container {width: 300px; padding: 10px; border: 1px solid # eee; box-sizing: border-box;} textarea {display: block; width: 100%; font-size: 20px Color: # 000; line-height: 24px; outline: none; border: none; resize: none;}

3. JS code:

Var textarea = document.querySelector ('textarea') var inpnt = (function () {var baseHeight = null return function () {! baseHeight & & (baseHeight = this.scrollHeight) this.rows = 1 var rows = Math.ceil (this.scrollHeight / baseHeight) > = 3? 3: Math.ceil (this.scrollHeight) / baseHeight) this.rows = rows}}) () textarea.oninput = debounce (inpnt Function debounce (func, delay) {var timer = null return function () {var _ this = this var args = arguments timer & & clearTimeout (timer) timer = setTimeout (function () {func.apply (_ this, args)} Delay)}}

Principle:

! baseHeight & & (baseHeight = this.scrollHeight) this.rows = 1 var rows = Math.ceil (this.scrollHeight / baseHeight) > = 3? 3: Math.ceil (this.scrollHeight / baseHeight) this.rows = rows

The first line gets the benchmark height cache

The second line focuses on setting the rows of textarea to 1 so that you can get the scrollHeight of the current textarea

After the third line gets the scrollHeight of the current textarea, you can calculate the rows.

The fourth line sets the rows of textarea

Change the height of the textarea by setting the textarea's rows property.

After reading this, the article "how to achieve a high degree of textarea adaptation" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, welcome to follow the industry information channel.

Tags: Height articles code content propriety one line principles benchmarks attributes ideas new knowledge methods more steps knowledge knowledge points articles details structure cache Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Redmi NVidia Shulou Tech Info Huawei