input 标签的宽度根据内容自动调整

通过 JavaScript 监听输入事件,临时将输入框宽度设为 auto 以获取内容真实宽度(scrollWidth),再将该宽度赋值给输入框,从而实现 "内容增减时宽度实时跟随"。

javascript 复制代码
<template>
  <div class="input-adaptive-container">
    <input 
      ref="inputRef"
      v-model="inputValue"
      class="adaptive-input"
      placeholder="请输入内容"
      @input="adjustWidth"
    >
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';

const inputRef = ref<HTMLInputElement | null>(null); // 输入框DOM引用
const inputValue = ref('啊啊啊啊啊事实上事实上事'); // 绑定的输入值

// 调整输入框宽度的核心方法
const adjustWidth = () => {
  const input = inputRef.value;
  if (!input) return;
  
  input.style.width = 'auto'; // 临时设为auto,获取真实内容宽度
  // scrollWidth 是内容实际宽度(含溢出),+2px 是缓冲避免文字贴边
  input.style.width = `${input.scrollWidth + 2}px`;
};

// 组件挂载后,初始化调整宽度(适配初始值)
onMounted(() => {
  nextTick(() => {
    adjustWidth();
  });
});
</script>

<style scoped>
.input-adaptive-container {
  text-align: center;
  padding: 20px;
}

.adaptive-input {
  padding: 6px 8px;
  border: 1px solid #000;
  border-radius: 2px;
  font-size: 16px;
  outline: none;
  box-sizing: border-box; /* 确保padding/border不影响宽度计算 */
  width: auto; /* 基础样式,实际宽度由JS动态控制 */
}
</style>