Svelte中使用fly过渡两段文本的UI问题修复求助
修复Svelte fly过渡导致的UI跳变问题
问题根源
第一种flex布局方案出现UI跳变,是因为{#key}触发过渡时,新旧文本元素会同时存在于DOM中一段时间,原span的my-24边距会让容器高度临时翻倍,导致下方按钮被挤压偏移。
修复方案(优先解决第一种方案的跳变)
给过渡文本添加一个固定高度的容器,让新旧元素都在容器内完成过渡,避免容器高度变化影响其他UI。修改后的代码如下:
<script lang="ts"> import { fly } from 'svelte/transition'; let value: string = ""; let question: string = 'First sentence'; </script> <div class="container text-center flex items-center justify-center flex-col"> <!-- 固定高度的容器,确保过渡期间布局稳定 --> <div class="relative h-24 w-full flex items-center justify-center"> {#key question} <span class="text-5xl" in:fly={{ y: 200, duration: 500 }} out:fly={{ y: -200, duration: 500 }}>{question}</span > {/key} </div> <form on:submit|preventDefault={() => { question = "Next sentence"; value = ""; }}> <button class="text-gray-400 text-sm my-4"> Press here to move to next sentence</button > </form> </div>
关键修改点
- 添加了
relative h-24 w-full flex items-center justify-center的容器:h-24固定容器高度(可根据文本大小调整,比如text-5xl用h-24足够容纳)flex items-center justify-center让文本在容器内垂直水平居中
- 移除了span上的
my-24:容器已经提供了垂直空间,避免margin导致的布局波动
第二种方案(绝对定位)的缩放问题修复
如果想用绝对定位方案,改用Tailwind的居中类确保不同缩放比例下的定位准确:
<script lang="ts"> import { fly } from 'svelte/transition'; let value: string = ""; let question: string = 'First sentence'; </script> <div class="container text-center flex items-center justify-center flex-col"> <div class="relative h-24 w-full"> {#key question} <span class="text-5xl absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2" in:fly={{ y: 200, duration: 500 }} out:fly={{ y: -200, duration: 500 }}>{question}</span > {/key} </div> <form on:submit|preventDefault={() => { question = "Next sentence"; value = ""; }}> <button class="text-gray-400 text-sm my-4"> Press here to move to next sentence</button > </form> </div>
关键说明
left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2是Tailwind的标准居中写法,基于transform实现,不会受浏览器缩放比例影响,能解决之前的缩放偏移问题。
内容的提问来源于stack exchange,提问作者dath.vg
相关产品推荐
相关产品推荐

