根据父元素类使用不同的@keyframes [英] Use different @keyframes based on parent element class

查看:228
本文介绍了根据父元素类使用不同的@keyframes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下动画:

@keyframes pulseColorGreen {
    0% {
        background-color: green;
    }
    97%{
        background-color: green;
    }
    100% {
      background-color: white;
    }
  }

我的网站也有深色背景,黑色。现在在动画中,我想显示一个深绿色,如下所示:

My website also has a dark mode where the background goes black. Now in the animation, I want to display a darker green just like below:

@keyframes pulseColorGreen {
    0% {
        background-color: darkgreen;
    }
    97%{
        background-color: darkgreen;
    }
    100% {
      background-color: black;
    }
  }

对于黑暗模式,我添加一个类 lightsOff在正文标签中。我正在使用目标元素类和 lightsOff类的组合来管理所有其他颜色更改,就像:

For the dark mode, I add a class "lightsOff" in the body tag. I am managing all other color changes using the combination of the target element class and "lightsOff" class just like:

.lightsOff .someclass{
    color: white
}

但是在CSS中定义元素时文件格式为:

But when defining an element in css file as:

@keyframes .lightsOff pulseColorGreen {
    0% {
        background-color: darkgreen;
    }
    97%{
        background-color: darkgreen;
    }
    100% {
      background-color: black;
    }
  }

给我一​​个错误,说期望标识符。我正在从javascript动态地将animation-name属性添加到元素。因此,我不希望更改JS代码来确定当前设置的主题并相应地设置关键帧。我该如何实现?

It gives me error saying "identifier expected". I am adding the animation-name property to elements dynamically from javascript. Hence, I won't prefer changing the JS code to identify which theme is set currently and set a keyframe accordingly. How can I achieve this?

推荐答案

您可以使用CSS变量,并且只需要一个关键帧更改。只需更改定义颜色的主类即可。

You can use CSS variable and you will need only one keyframes that you don't have to change. Simply change the main class that define the color:

.light {
  --c: yellow;
}

.dark {
  --c: darkblue;
}

.box {
  height: 100px;
  margin: 5px;
  box-shadow: 0 0 5px var(--c);
  color:#fff;
  animation: pulseColorGreenMkt 1s infinite linear alternate;
}

@keyframes pulseColorGreenMkt {
  0% {
    background-color: var(--c);
  }
  100% {
    background-color: black;
  }
}

<div class="box light">
  Class defined on the element
</div>
<div class="dark">
  <div class="box">
    Class defined on a parent element
  </div>
</div>

这篇关于根据父元素类使用不同的@keyframes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆