首页 > 解决方案 > CSS动画自定义属性/变量

问题描述

我一直试图让它工作一段时间。

关键是内部 div 会有一些形状,而且可能不止一个(这就是我使用nth-child选择器的原因)。这个内部 div 应该被显示,然后在一段时间内再次隐藏。问题是,我想在一个动画中为所有(后来的)多个内部 div 设置动画。为此,我认为我可以使用 CSS 变量,但这似乎不起作用。

在这个例子中我试图归档的是内部 div 基本上只是通过使用变量来闪烁。但我在 Firefox 中的结果只是一个黑匣子。

我错过了什么吗?我已经查过是否可以在其中使用 CSS 变量,@keyframes并且确实可以。它们在动画中的唯一问题似乎是它们没有在两者之间进行插值,而是它们突然切换,在这种情况下这不是问题。

@keyframes test{
    from{
        --one: 0;
    }
    to{
        --one: 1;
    }
}

#test{
    width: 100px;
    height: 200px;
    background-color: black;
    animation: test 1s infinite;
}
#test :nth-child(1){
    width: 20px;
    height: 20px;
    margin: auto;
    background-color: white;
    opacity: var(--one,0);
}
<div id="test">
    <div></div>
</div>

标签: htmlcsscss-animationscss-variables

解决方案


这可以通过使用定义变量来实现(截至撰写本文时,还没有得到很好的支持)@property,它允许声明类型并允许浏览器“理解”,例如,某个属性(变量)是一个数字,然后它可以逐渐动画/过渡该变量。

示例代码:

@property --opacity {
  syntax: '<number>'; /* <- defined as type number for the transition to work */
  initial-value: 0;
  inherits: false;
}

@keyframes fadeIn {
  50% {--opacity: 1}
}

html {
  animation: 2s fadeIn infinite;
  background: rgba(0 0 0 / var(--opacity));
}

当前允许的类型包括:

length, number, percentage, length-percentage, color, image, url, integer, angle, time, resolution, transform-list, transform-function, custom-ident(标识符字符串)


有用的文章:

  1. https://web.dev/at-property/#writing-houdini-custom-properties
  2. https://css-tricks.com/using-property-for-css-custom-properties
  3. 酷胡迪尼演示

推荐阅读