Make an example code of textarea that can adapt to the height

Time:2020-2-15

Method

1. HTML structure:


    <div id="container">
        <textarea rows="1"></textarea>
    </div>

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, 100)

        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 reference height from the cache

The second line focuses on setting the rows of textarea to 1 so as to get the scrollheight of the current textarea

The third line gets the scroll height of the current textarea and calculates the rows

The fourth line sets the rows of textarea

Change the height of textarea by setting the rows attribute of textarea.

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.

Recommended Today

What is Baidu’s secure openrasp project?

What is Baidu‘s secure openrasp project? In the history of this article, the official account is from the public technology. Welcome to redistribute and share knowledge, and respect copyright tagging authors and sources. At the end of the conversation, c0debreak opened a “confidential document” for me to see. It’s a secret that a otaku has […]