我想制作一个动画标签:
我正在使用 React 和 Tailwind。这是我的代码:
import React from 'react'
import clsx from 'clsx'
export const Modal = () => {
const [theme, setTheme] = React.useState<'light' | 'dark' | 'system'>('light')
return (
<div className="flex mx-2 mt-2 rounded-md bg-blue-gray-100">
<div
className={clsx('flex-1 py-1 my-2 ml-2 text-center rounded-md', {
'bg-white': theme === 'light',
'transition duration-1000 ease-out transform translate-x-10':
theme !== 'light',
})}
>
<button
className={clsx(
'w-full text-sm cursor-pointer select-none focus:outline-none',
{
'font-bold text-blue-gray-900': theme === 'light',
'text-blue-gray-600': theme !== 'light',
}
)}
onClick={() => {
setTheme('light')
}}
>
Light
</button>
</div>
<div
className={clsx('flex-1 py-1 my-2 ml-2 text-center rounded-md', {
'bg-white': theme === 'dark',
})}
>
<button
className={clsx(
'w-full text-sm cursor-pointer select-none focus:outline-none',
{
'font-bold text-blue-gray-900': theme === 'dark',
'text-blue-gray-600': theme !== 'dark',
}
)}
onClick={() => {
setTheme('dark')
}}
>
Dark
</button>
</div>
<div
className={clsx('flex-1 py-1 my-2 mr-2 text-center rounded-md', {
'bg-white': theme === 'system',
})}
>
<button
className={clsx(
'w-full text-sm cursor-pointer select-none focus:outline-none',
{
'font-bold text-blue-gray-900': theme === 'system',
'text-blue-gray-600': theme !== 'system',
}
)}
onClick={() => {
setTheme('system')
}}
>
System
</button>
</div>
</div>
)
}
但它看起来像:
当主题不是 light
时我使用 translate-x-10
,因此文本也会移动。
我很乐意让 UI 与上面的完全一样,同时仍然为实际的选项卡使用按钮。
最小代码沙箱 → https://codesandbox.io/s/mobx-theme-change-n1nvg?file=/src/App.tsx
我该怎么做?
最佳答案
你可以很容易地做这个动画,你需要在包含三个按钮的父元素中添加另一个标签元素。
因此,此元素将跟踪哪个按钮处于事件状态,并根据按钮的宽度移动。
例如,如果第一个按钮处于事件状态,则根本不会翻译该元素,因为它是第一个元素,所以位置将为 0。
这个将执行动画的元素将具有绝对定位,如下所示:
.tab-item-animate {
position: absolute;
top: 6px;
left: 6px;
width: calc(100% - 12px);
height: 32px;
transform-origin: 0 0;
transition: transform 0.25s;
}
激活的第一个按钮:
.tabs .tabs-item:first-child.active ~ .tab-item-animate {
transform: translateX(0) scaleX(0.333);
}
第二个按钮激活:
.tabs .tabs-item:nth-child(2).active ~ .tab-item-animate {
transform: translateX(33.333%) scaleX(0.333);
}
第三个按钮处于事件状态:
.tabs .tabs-item:nth-child(3).active ~ .tab-item-animate {
transform: translateX(33.333% * 2) scaleX(0.333);
}
我对 Tailwind 没有太多经验,但我不确定你是否可以用它来管理整个事情(也许你可以用我的代码做一些其他操作,只用 Tailwind 来完成)。
我为此添加了一个单独的 CSS 文件,我根据您共享的代码提供了一个演示:
PS:我已经稍微改变了你的 HTML 结构,你不需要在每个按钮上方添加另一个 div,这是没有必要的。
关于html - 在 Tailwind CSS 中制作动画标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66279676/