插件窝 干货文章 Element Plus el-input textarea如何自适应内容并撑满父容器?

Element Plus el-input textarea如何自适应内容并撑满父容器?

textarea 容器 高度 height 189    来源:    2025-03-19

在 Element Plus 中,el-input 组件支持 textarea 类型的输入框。要实现 textarea 自适应内容并撑满父容器,可以通过以下步骤实现:

1. 使用 autosize 属性

el-input 组件提供了一个 autosize 属性,可以自动调整 textarea 的高度以适应内容。你可以将 autosize 设置为 true 或者一个包含 minRowsmaxRows 的对象。

<template>
  <el-input
    type="textarea"
    :autosize="{ minRows: 2, maxRows: 6 }"
    v-model="inputText"
  ></el-input>
</template>

<script>
export default {
  data() {
    return {
      inputText: ''
    };
  }
};
</script>

2. 使用 CSS 撑满父容器

如果你希望 textarea 撑满父容器的高度,可以使用 CSS 来实现。你可以将 textarea 的高度设置为 100%,并确保父容器有明确的高度。

<template>
  <div class="container">
    <el-input
      type="textarea"
      :autosize="{ minRows: 2 }"
      v-model="inputText"
      class="full-height-textarea"
    ></el-input>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputText: ''
    };
  }
};
</script>

<style scoped>
.container {
  height: 300px; /* 父容器的高度 */
  display: flex;
  flex-direction: column;
}

.full-height-textarea {
  flex: 1;
}

.full-height-textarea textarea {
  height: 100%;
}
</style>

3. 动态调整高度

如果你希望 textarea 的高度根据内容动态调整,并且撑满父容器,可以结合 autosize 和 CSS 来实现。

<template>
  <div class="container">
    <el-input
      type="textarea"
      :autosize="{ minRows: 2 }"
      v-model="inputText"
      class="dynamic-height-textarea"
    ></el-input>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputText: ''
    };
  }
};
</script>

<style scoped>
.container {
  height: 300px; /* 父容器的高度 */
  display: flex;
  flex-direction: column;
}

.dynamic-height-textarea {
  flex: 1;
}

.dynamic-height-textarea textarea {
  height: 100%;
  resize: none; /* 禁止用户手动调整大小 */
}
</style>

4. 注意事项

  • autosize 属性会根据内容自动调整 textarea 的高度,但如果你希望 textarea 撑满父容器的高度,需要结合 CSS 来实现。
  • 如果父容器的高度是动态变化的,你可能需要使用 JavaScript 来监听父容器的高度变化,并动态调整 textarea 的高度。

通过以上方法,你可以实现 el-inputtextarea 自适应内容并撑满父容器。