代码之家  ›  专栏  ›  技术社区  ›  Dan

如何使用Tailwind创建动画序列?

  •  0
  • Dan  · 技术社区  · 1 年前

    我有以下要素:

    <div dir="rtl" class="aspect-ratio-1 group relative h-min w-full max-w-[300px] flex-shrink-0 lg:max-w-[390px]">
      <img class="rounded-s-full border-[12px] border-indigo-400" alt="Placeholder" src="https://placehold.co/400x600" />
    </div>
    

    我想用《顺风》制作一个动画序列。

    对于序列,首先 rounded-s-full 应该需要0.3秒才能以平滑的方式施加,之后, border-[12px] 应该需要0.3秒才能“生长”。我想知道这是否可以通过Tailwind实现。在文档中,我只能找到如何将转换应用于特定属性,并且可以找到任何延迟动画的方法。

    2 回复  |  直到 1 年前
        1
  •  0
  •   yttap    1 年前

    可以通过定义自定义CSS类并使用transition属性指定转换的持续时间来创建动画序列。也可以使用延迟属性来延迟动画。

    <div dir="rtl" class="aspect-ratio-1 group relative h-min w-full max-w-[300px] flex-shrink-0 lg:max-w-[390px]">
      <img class="rounded-full animation1" alt="Placeholder" src="https://placehold.co/400x600" />
    </div>
    

    在您的CSS中(您可以将其添加到现有的CSS文件中,或者如果您将Tailwind CSS与PostCSS一起使用,则可以使用@applywithPostCSS之类的工具),定义动画类

    @keyframes growBorder {
      0% {
        border-width: 0;
      }
      100% {
        border-width: 12px;
      }
    }
    
    @keyframes smoothRounded {
      0% {
        border-radius: 0;
      }
      100% {
        border-radius: 50%;
      }
    }
    
    .animation1 {
      animation-name: smoothRounded, growBorder;
      animation-duration: 0.3s, 0.3s;
      animation-timing-function: ease, ease;
      animation-fill-mode: both, both;
      animation-delay: 0s, 0.3s; /* Delay the border animation by 0.3s */
    }
    
        2
  •  0
  •   George    1 年前

    或者,您可以通过扩展主题配置,以“顺风方式”进行此操作。具体来说,添加到 keyframes animation 属性:

    export default {
      theme: {
        extend: {
          keyframes: {
            semicircle: {
              '0%': {
                borderWidth: '0',
                borderStartStartRadius: '0',
                borderEndStartRadius: '0'
              },
              '50%': {
                borderWidth: '0',
                borderStartStartRadius: '50%',
                borderEndStartRadius: '50%'
              },
              '100%': {
                borderWidth: '12px',
                borderStartStartRadius: '50%',
                borderEndStartRadius: '50%'
              },
            },
          },
          animation: {
            semicircle: 'semicircle 0.6s forwards',
          },
        },
      },
    }
    

    然后用调用动画 animation-semicircle 类别:

    <div dir="rtl" class="aspect-ratio-1 group relative h-min w-full max-w-[300px] flex-shrink-0 lg:max-w-[390px]">
      <img class="animate-semicircle border-indigo-400" alt="Placeholder" src="https://placehold.co/400x600" />
    </div>
    

    不幸的是,无法可靠地设置“完整”边界半径的动画-Tailwind使用了一种破解方法,将完整边界半径指定为 9999px 。你可以想象,试图让CSS在0.3秒内将边界半径从0px动画化到9999px,会产生非常快速的快照。

    参考文献: