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

如何实现带动画的文本块拆分与对齐效果?

解决方案

要实现两段文本的两种状态切换且保持正确对齐,核心是通过容器统一控制状态一的整体居中,状态二时让文本各自独立定位。以下是修改后的代码:

Vue 模板

<template>
  <button v-on:click="change_solved">Solve</button>
  <div class="title-container" :class="{active: solved}">
    <h1 class="cat_num">Text 1</h1>
    <h1 class="cat_name">Text 2 (possibly lengthy)</h1>
  </div>
</template>

JavaScript

export default {
  name: 'App',
  data() {
    return {
      solved: false,
    };
  },
  methods: {
    change_solved() {
      this.solved = !this.solved;
    },
  },
};

CSS

/* 状态一:容器整体居中,文本并排 */
.title-container {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  transition: all 2s ease;
  text-align: center;
}

.cat_num, .cat_name {
  display: inline-block;
  margin: 0 8px; /* 可选:给文本间添加间距 */
  transition: all 2s ease;
}

/* 状态二:文本各自独立居中到指定位置 */
.title-container.active .cat_num {
  position: fixed;
  top: 100px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 40px;
}

.title-container.active .cat_name {
  position: fixed;
  top: 200px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 50px;
}

关键修改说明

  1. 状态一的共同居中:用title-container包裹两段文本,通过position: fixed+top/left:50%+transform: translate(-50%, -50%)实现容器整体居中,内部文本设为inline-block即可并排显示,且整体对齐页面中心。
  2. 状态二的单独居中:激活.active类后,给每个文本单独设置position: fixed,同样用left:50%+transform: translateX(-50%)实现自身水平居中,再通过top属性定位到不同垂直位置。
  3. 过渡保留:容器和文本都保留了transition属性,确保状态切换时的平滑动画。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 07:18:16