我写一个模仿你说的效果代码
代码如下:
点击查看全文
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link type="text/css" rel="stylesheet" href="//repo.bfw.wiki/bfwrepo/css/layui.2.8.9.css"> <style> .textarea-container { position: relative; flex:1; } textarea { width: 100%; background: white; line-height: 20px; box-sizing: border-box; padding: 8px; font-family: inherit; font-size: 16px; resize: none; overflow: hidden; border: none; outline: none; height: 40px; } textarea:focus { border: none; outline: none; } textarea::placeholder { } .hidden-textarea { visibility: hidden; white-space: pre-wrap; word-wrap: break-word; position: absolute; top: 0; left: 0; z-index: -1; width: 100%; padding: 8px; box-sizing: border-box; font-size: 16px; line-height: 20px; } .scrollable { overflow-y: auto; max-height: calc(1.5em * 5 + 16px); } .input-panel{ background: white; border: 1px solid grey; border-radius: 15px; display:flex; margin: 10px; align-items: flex-end; } </style> </head> <body> <div id="app"> <div style="" class="input-panel"> <i class="layui-icon layui-icon-add-circle" style="margin:15px;"></i> <div class="textarea-container"> <textarea placeholder="请输入" v-model="text" @keydown="resizeTextarea" @keyup="resizeTextarea" :class="{ scrollable: isScrollable }"></textarea> <div class="hidden-textarea" ref="hiddenText">{{ text }}</div> </div> <!-- 发送按钮 --> <i class="layui-icon layui-icon-share" style="margin:15px;"></i> </div> <p>Text width: {{ textWidth }}px</p> </div> <!-- 引入Vue.js CDN --> <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/vue@2.6.1-dev.js"></script> <script> new Vue({ el: '#app', data: { text: '', textWidth: 0, isScrollable: false }, methods: { resizeTextarea() { const hiddenText = this.$refs.hiddenText; const textarea = this.$el.querySelector('textarea'); if(this.text==""){ textarea.style.height = '40px'; return; } // 设置隐藏元素的高度等于textarea内容的高度 hiddenText.style.height = 'auto'; hiddenText.style.height = hiddenText.scrollHeight + 'px'; // 将textarea的高度设置为隐藏元素的高度 textarea.style.height = 'auto'; textarea.style.height = hiddenText.scrollHeight + 'px'; // 检查是否需要显示滚动条 this.isScrollable = hiddenText.scrollHeight > 5 * parseFloat(getComputedStyle(hiddenText).lineHeight); // 更新文本宽度 this.textWidth = hiddenText.offsetWidth; } } }); </script> </body> </html>
网友回复