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

Vue out-in过渡优化:如何让Block2在Block1平移50%时启动?

解决方案

要实现Block1平移至50%时Block2开始显示,你需要调整Vue过渡的模式和动画时序,同时修正元素定位避免布局冲突,具体修改如下:

修改后的完整代码

<template>
  <div id="app">
    <button @click="show = !show">Click Me!</button>
    <transition>
      <div class="block" id="block-1" v-if="show">Block 1</div>
      <div class="block" id="block-2" v-else>Block 2</div>
    </transition>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return { show: true };
  },
};
</script>

<style>
body {
  font-family: 微軟正黑體;
}
button {
  margin-bottom: 10px;
}

#block-1 {
  background-color: yellow;
  color: black;
}

#block-2 {
  background-color: green;
}

#app {
  padding: 10px;
  background-color: gray;
  overflow: hidden;
  position: relative; /* 新增:作为绝对定位元素的容器 */
}

.block {
  background: #999;
  color: #fff;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px; /* 替换table-cell,适配绝对定位的垂直居中 */
  position: absolute; /* 新增:让两个块在同一位置渲染 */
  top: 10px; /* 对应父容器的padding-top,保持位置一致 */
}

.v-leave-from {
  transform: translateX(0%);
}
.v-leave-active {
  transition: transform 1s;
}
.v-leave-to {
  transform: translate(-220%);
}
.v-enter-from {
  transform: translateX(600%);
}
.v-enter-active {
  transition: transform 2s;
  transition-delay: 0.5s; /* 新增:等待0.5秒(离开动画的一半时长)再开始进入 */
}
.v-enter-to {
  transform: translateX(0%);
}
</style>

关键修改说明

  1. 移除mode="out-in":原属性会强制等待Block1的离开动画完全结束后,才触发Block2的进入动画,移除后允许两个动画部分重叠。
  2. 调整元素定位:通过父容器相对定位、子元素绝对定位,确保两个Block始终在同一位置渲染,避免因DOM同时存在导致的布局错乱。
  3. 添加进入动画延迟:Block1的离开动画时长为1秒,设置transition-delay: 0.5s后,Block2会在Block1平移至50%进度时开始进入动画,完美匹配你的需求。
  4. 替换垂直居中方式:绝对定位下display: table-cell无法正常工作,改用line-height实现垂直居中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 22:41:27