實現(xiàn)一個高度和寬度自動擴展的文本輸入組件

要求,完成一個高度和寬度自動擴展的文本輸入組件如圖所示


pic01.gif

主要思想是textarea的長度和高度分別用一個隱藏的div和一個隱藏的textarea去獲取,然后把獲取到的長度和高度放入我們的textarea,就實現(xiàn)了這個要求,下面附上代碼(用vue實現(xiàn),原生同理)。

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>自動擴展的文本輸入</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <style>
        textarea {
            resize: none;
            font-family: Arial, Helvetica, sans-serif;
            font-size: 16px;
        }

        #bk {
            width: 500px;
            padding: 5px;
            border-style: solid;
            border-color: red;
            border-width: 1px 1px 1px 1px;
        }

        div {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 16px;
        }
    </style>
</head>

<body>
    <div id="app">
        <div id="bk">
            <textarea @focus="textFocus" type="text" v-model="content" ref="input"
                :style="{height: teaxtAreaHeight,width: teaxtAreaWidth}" rows="1"
                style="overflow-y: hidden;"></textarea>
        </div>
        <textarea style="position: absolute; visibility:hidden; width: 500px;" ref="heightRuler" v-model="content"
            rows="1"></textarea>
        <div style="position: absolute;visibility:hidden;" ref="widthRuler">{{content}}</div>
    </div>
</body>
<script type="text/javascript">
    var app = new Vue({
        el: '#app',
        data: {
            content: '',
            teaxtAreaHeight: '',
            teaxtAreaWidth: '120px'
        },
        methods: {
            textFocus() {
                document.addEventListener('keyup', () => {
                    this.$nextTick(() => {
                        const width = (this.$refs.widthRuler).offsetWidth + 10;
                        console.log(width);
                        if (width !== this.teaxtAreaWidth && width < 500 && width > 120) {
                            this.teaxtAreaWidth = width + 'px';
                        }
                        const height = `${(this.$refs.heightRuler).scrollHeight}px`;
                        if (height !== this.teaxtAreaHeight) {
                            this.teaxtAreaHeight = height;
                        }
                    });
                });
            }
        }
    })
</script>

</html>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容