如何实现input宽度随内容自适应

755 阅读1分钟

Situation

我们在开发中,常常会遇到需要和用户交互的场景,input就是其中之一

最近的开发中,遇到这么一个需求,希望input宽度随着用户的输入内容自适应,同时设置最大宽度为500px

Task

input标签不像div标签可以通过flex布局等方式实现宽度自适应,如果从input上无从下手,我们倒是可以考虑下其他可以实现同一效果的方式

Action

input本身宽度无法自适应,但我们可以让它随着父元素变化,给个span标签撑大宽度,这样把span标签隐藏在input下面,就能实现宽度自适应了

<template>
    <div class="input-wrap">
        <span>{{ input }}</span>
        <input
            placeholder="请输入姓名"
            v-model="input"
            class="input"
        />
    </div>
</template>
<style scoped lang="scss">
.input-wrap {
    position: relative;
}
span {
    display: inline-block;
    height: 100%;
    background: inherit;
    padding: 0;
    white-space: nowrap;
    opacity: 0;
    box-sizing: border-box;
    padding: 4px 6px;
    border-radius: 6px;
    max-width: 100px;
}
input {
    border: 1px solid black;
    position: absolute;
    left: 0;
    top:0;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    padding: 4px 6px;
    border-radius: 6px;
}
</style>

设置input最大宽度为100px,当我们输入内容长度不超过100px时,input宽度自适应,直到100px

2024-07-08 15.21.07.gif

div标签也能实现同样的效果,实现方式大同小异,此处不再赘述