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

Tailwind自定义Switch组件切换过渡失效问题求助

解决Tailwind CSS自定义Switch组件过渡动画失效问题

你的推测没错,right-1和left-1的切换确实是过渡失效的核心原因——这两个类分别设置了right: 0.25rem和left: 0.25rem,但元素无法同时拥有非auto的left和right属性值,浏览器无法在这两个状态间生成平滑过渡动画。

修复方案:用transform替代定位属性切换

改用transform: translateX()控制滑块位置,这个属性属于可过渡的CSS属性,配合transition-all就能实现平滑动画效果。

修正后的组件代码:

import type { StateUpdater } from "preact/hooks"

type SwitchButtonProps = {
    textLeft: string,
    textRight: string,
    isSwitched: boolean,
    setIsSwitched: StateUpdater<boolean>
}

export const SwitchButton = ({ textLeft, textRight, isSwitched, setIsSwitched }: SwitchButtonProps) => {
    return (
        <div class="mx-8 shadow rounded border h-10 mt-4 flex p-1 relative items-center bg-gray-200">
            <div class="w-full flex justify-center" onClick={() => setIsSwitched(false)}>
                <button>{textLeft}</button>
            </div>
            <div class="w-full flex justify-center" onClick={() => setIsSwitched(true)}>
                <button>{textRight}</button>
            </div>
            <span
                class={`bg-white shadow text-gray-800 flex items-center justify-center w-1/2 rounded h-8 transition-all top-[4px] absolute left-1
                ${isSwitched ? 'translate-x-full' : ''}
                `}>
                {isSwitched ? textRight : textLeft}
            </span>
        </div>
    )
}

关键改动说明:

  • 移除right-1和left-1的条件切换,给滑块固定设置left-1作为初始左偏移
  • 用translate-x-full替代right-1:当切换状态为true时,滑块沿X轴平移自身宽度的距离,刚好到达右侧对应位置
  • 保留transition-all,确保平移过程有平滑过渡
  • 修正TypeScript类型:字符串类型统一用小写string而非String

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:02:10