You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修复Vue3相邻元素过渡动画:按钮跳转异常问题

修复按钮突然跳转的过渡问题

问题出在你只给textarea容器加了透明度过渡,但元素离开时是直接从DOM中移除的,高度没有平滑变化——取消勾选时,textarea容器只是变透明,高度还在,过渡结束后瞬间消失,按钮就会突然往上跳。

解决方法很简单,给textarea容器加上高度过渡,让它在消失时逐渐收缩高度到0,同时处理内容溢出:

<script setup>
import { ref } from "vue";

const showNote = ref(false);
const toggleCheckbox = () => {
  showNote.value = !showNote.value;
};
</script>

<template>
  <div class="add-note">
    <div class="flex align-items-center">
      <input type="checkbox" :checked="showNote" @click="toggleCheckbox"/>
      <label>Show note</label>
    </div>
    <Transition>
      <div v-if="showNote" class="note-area">
        <div class="form-item-full-width">
          <textarea id="w3review" name="w3review" rows="4" cols="50"></textarea>
        </div>
      </div>
    </Transition>
  </div>
  <!-- 移除按钮的Transition组件,按钮位置变化由上方容器过渡自然带动 -->
  <div class="form-body">
    <div class="form-item-full-width">
      <button type="button">Submit data</button>
    </div>
  </div>
</template>

<style>
.v-enter-active,
.v-leave-active {
  /* 同时过渡透明度和高度,保持时长一致 */
  transition: opacity 0.5s ease, max-height 0.5s ease;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
  /* 离开时将最大高度设为0 */
  max-height: 0;
}

.v-enter-to,
.v-leave-from {
  /* 进入时设一个足够大的最大高度,覆盖textarea的实际高度 */
  max-height: 200px;
}

.note-area {
  /* 隐藏溢出内容,避免收缩时textarea显示不全 */
  overflow: hidden;
}
</style>

原理说明:

  • 用max-height代替height做过渡,因为textarea的高度是由rows决定的,用max-height可以适配不同内容高度,避免固定高度的局限性。
  • 过渡时同时处理透明度和max-height,让容器在消失时逐渐变透明+收缩高度,按钮会随着容器高度的平滑变化自然移动,不会突然跳转。
  • 移除按钮的Transition组件,因为按钮本身不需要独立过渡,它的位置变化是页面布局自然流动的结果,单独加Transition反而会导致冲突。

内容的提问来源于stack exchange,提问作者Mr.P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 12:40:28