el-input 输入框宽度自适应宽度

利用一个隐藏的 <span>(称为 mirror)渲染当前输入内容:

  1. span 使用与 <el-input> 相同的字体样式;

  2. 每次输入时,根据 span.offsetWidth 动态计算内容宽度;

  3. 将该宽度赋给 <el-input>style.width

  4. 给输入框增加少许 padding 余量,保证视觉舒适。

    <template> <el-form :model="form" label-width="auto" class="auto-form"> <el-form-item label="Activity name">
    {{ form.name || placeholder }}
    复制代码
         <!-- 自适应宽度的 el-input -->
         <el-input
           v-model="form.name"
           :style="{ width: inputWidth + 'px' }"
           :placeholder="placeholder"
           class="auto-el-input"
           @input="updateWidth"
         />
       </div>
     </el-form-item>
    
     <el-form-item>
       <el-button type="primary" @click="onSubmit">Create</el-button>
       <el-button @click="onCancel">Cancel</el-button>
     </el-form-item>
    </el-form> </template> <script lang="ts" setup> import { ref, reactive, onMounted, nextTick } from 'vue'

    // 表单数据
    const form = reactive({
    name: ''
    })

    // 占位文字(用于在空值时计算最小宽度)
    const placeholder = '请输入活动名称'

    // 输入框宽度(默认最小 100px)
    const inputWidth = ref(100)
    const mirror = ref<HTMLElement | null>(null)

    // 动态更新输入框宽度
    const updateWidth = () => {
    if (mirror.value) {
    // 同步文字
    mirror.value.textContent = form.name || placeholder
    // 计算宽度 + 内边距
    inputWidth.value = mirror.value.offsetWidth + 24
    }
    }

    onMounted(async () => {
    await nextTick()
    updateWidth()
    })

    const onSubmit = () => {
    console.log('提交数据:', form)
    }

    const onCancel = () => {
    form.name = ''
    updateWidth()
    }
    </script>

    <style scoped> .auto-form { max-width: 500px; margin: 40px auto; }

    .input-auto-wrapper {
    display: inline-block;
    position: relative;
    }

    .mirror {
    position: absolute;
    visibility: hidden;
    white-space: pre;
    font: inherit; /* 与 el-input 保持一致 */
    padding: 0 12px;
    }

    .auto-el-input {
    transition: width 0.2s ease;
    }
    </style>

限制最大宽度

复制代码
inputWidth.value = Math.min(mirror.value.offsetWidth + 24, 400)

此方案无需修改 Element Plus 源码,通过一个简单的隐藏 span 即可实现原生级别的动态自适应宽度输入框效果

相关推荐
ssshooter12 小时前
看完就懂 useSyncExternalStore
前端·javascript·react.js
Live0000013 小时前
在鸿蒙中使用 Repeat 渲染嵌套列表,修改内层列表的一个元素,页面不会更新
前端·javascript·react native
柳杉13 小时前
使用Ai从零开发智慧水利态势感知大屏(开源)
前端·javascript·数据可视化
球球pick小樱花14 小时前
游戏官网前端工具库:海内外案例解析
前端·javascript·css
前端Hardy14 小时前
干掉 Virtual DOM?尤雨溪开始"强推" Vapor Mode?
vue.js·vue-router
喝水的长颈鹿14 小时前
【大白话前端 02】网页从解析到绘制的全流程
前端·javascript
用户145369814587814 小时前
VersionCheck.js - 让前端版本更新变得简单优雅
前端·javascript
codingWhat14 小时前
整理「祖传」代码,就是在开发脚手架?
前端·javascript·node.js
码路飞14 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python