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

Vue中实现.add-todo按钮与.new-todo表单的平滑联动动画

解决按钮平滑下移的问题

问题核心是表单的显示/隐藏有过渡动画,但按钮的位置变化是因为布局突然被表单占据空间导致的,没有给按钮添加过渡效果。以下是两种可行解决方案:

方案一:统一容器过渡(推荐)

将表单和按钮放入同一个容器,让容器的高度变化触发过渡,从而带动按钮平滑移动:

<script setup>
import { ref } from 'vue'
let isAddingTodo = ref(false)
</script>

<template>
  <div class="todo-container">
    <transition name="fade">
      <div
        v-if="isAddingTodo"
        class="new-todo p-3 border border-2 border-secondary rounded-3 mt-2 mb-2 d-flex justify-content-between align-items-center"
      >
        <!-- 表单内容示例 -->
        <input type="text" placeholder="输入新待办" class="flex-grow-1 me-2">
        <button class="btn btn-primary">添加</button>
      </div>
    </transition>

    <div
      class="add-todo p-3 d-flex rounded-3 mb-2 border border-2 border-white"
      @click="isAddingTodo = !isAddingTodo"
    >
      <i class="fi fi-br-plus mx-auto"></i>
    </div>
  </div>
</template>

<style>
.todo-container {
  overflow: hidden;
  transition: height 0.5s ease;
}

.fade-enter-active,
.fade-leave-active {
  transition: all 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(-69px);
}
</style>

方案二:给按钮单独添加过渡

通过动态绑定样式,让按钮在表单显示时同步执行下移动画:

<script setup>
import { ref } from 'vue'
let isAddingTodo = ref(false)
</script>

<template>
  <transition name="fade">
    <div
      v-if="isAddingTodo"
      class="new-todo p-3 border border-2 border-secondary rounded-3 mt-2 mb-2 d-flex justify-content-between align-items-center"
    >
      <!-- 表单内容示例 -->
      <input type="text" placeholder="输入新待办" class="flex-grow-1 me-2">
      <button class="btn btn-primary">添加</button>
    </div>
  </transition>

  <div
    class="add-todo p-3 d-flex rounded-3 mb-2 border border-2 border-white"
    @click="isAddingTodo = !isAddingTodo"
    :style="{ 
      transition: 'transform 0.5s ease',
      transform: isAddingTodo ? 'translateY(69px)' : 'translateY(0)'
    }"
  >
    <i class="fi fi-br-plus mx-auto"></i>
  </div>
</template>

<style>
.fade-enter-active,
.fade-leave-active {
  transition: all 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(-69px);
}
</style>

说明

  • 方案一利用容器高度的自然变化+过渡,更符合布局逻辑,无需手动计算位移值
  • 方案二需要手动匹配表单的位移距离(示例中为69px),适合布局结构简单的场景

内容的提问来源于stack exchange,提问作者Okinea Dev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 16:33:15