input框实现宽度随内容自适应
实现一:vue中的v-model + vue-input-autowidth插件
1.npm i vue-input-autowidth。
2.在main.js中import, 并使用Vue.use()。
3.封装组件,带有label的input组件;使用<AutoWidthInput :label="名称", v-model="value" />
<template> <div class="autoInputContainer"> <label class="inputLable">{{label}}</label> <div style="display: inline-block" @mouseenter="enter" @mouseleave="leave"> <input type="text" v-autowidth="{maxWidth: '500px', minWidth: '78px', comfortZone: 0}" placeholder="请输入" class="autoInput" @input="update" :value="value" @blur="inputBlur" @focus="inputFocus" ref="input" /> <i class="el-icon-circle-close close" @click="clearValue" v-show="closeDisable"></i> </div> </div> </template> <script> export default { name: 'AutoWidthInput', model: { prop: 'value', event: 'input' }, props:{ value:{ type:[ Number , String], default:'' }, label:{ type:[ String], default:'' } }, data() { return { closeDisable: false, isFocus:false // input框是否聚焦 }; }, methods: { update(e){ this.$emit('input',e.target.value) if(e.target.value!==''){ this.closeDisable = true // 显示清空按钮 } }, clearValue(){ this.$emit('input','') this.$refs.input.focus() }, inputBlur(){ }, inputFocus(e){ this.isFocus = true if(e.target.value!==''){ this.closeDisable = true } }, // hover效果 enter (e){ if(this.value!==''){ this.closeDisable = true } }, leave (e){ this.closeDisable = false } } }; </script> <style lang="scss" scoped> .autoInputContainer{ position: relative; padding: 5px 0; float: left; margin-right: 15px; label{ font-size: 13px; display: inline-block; padding-right: 15px;; } .autoInput{ box-sizing: border-box; color: #606266; display: inline-block; font-size: inherit; height: 32px; line-height: 12px; background-color: #FFF; background-image: none; border-radius: 4px; border: 1px solid #DCDFE6; white-space: nowrap; font-size: 12px; padding: 0 10px; padding-right: 20px; } .autoInput:hover{ border-color: #C0C4CC } .close{ position: absolute; top: 50%; transform: translateY(-50%); right: 5px; font-size: 14px; cursor: pointer; color: #DCDFE6; } .close:hover{ color: #979b9f; } } </style>
实现二:利用html5中的contenteditable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <div contenteditable= "true" class = "inputWidth" @input= "change" ref= "input1" >{{input}}</div> </div> </template> <script setup> import {ref} from 'vue' const input = ref( '' ) const input1 = ref( null ) console.log( 'input1:' ,input1) const change = ()=> { input.value = input1.value.innerHTML console.log(input.value) } </script> <style scoped> .inputWidth{ display: inline-block; min-width: 100px; max-width: 500px; border: 1px solid #ccc; padding: 10px; white-space: nowrap; } </style> |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix