同步 CSS 动画

3

有没有可能同步CSS动画?例如,

我有这个动画:

@keyframes AnimatedGradient {
    0% {
        background-position: 0% 50%
    }
    50% {
        background-position: 100% 50%
    }
    100% {
        background-position: 0% 50%
    }
}

我使用这个类将其应用于任何想要的元素:

.animated-gradient {
    background: linear-gradient(270deg, #FC5C7D, #6A82FB, #EB3349, #F45C43, #FF8008, #FFC837, #4CB8C4, #3CD3AD, #24C6DC, #514A9D, #FF512F, #DD2476, #DA22FF, #9733EE, #22c1c3, #fdbb2d);
    background-size: 3200% 3200%;
    animation: AnimatedGradient 160s linear infinite;
}

如果我将它应用于两个或更多元素,例如第一个是背景(body标签),另一个是悬停按钮,那么当我悬停在按钮上时,动画会从头开始,但我希望它与背景同步。那么我该怎么做呢?最好使用纯JavaScript。谢谢!
1个回答

3
也许你可以在鼠标悬停时使按钮的背景透明。下面的代码片段可能会有所帮助。在这个片段中,我给按钮加了一个粗边框,以便在悬浮时能看到它,但是你也可以使用其他适合你代码的技术(比如裁剪或在div之间堆叠按钮)。

@keyframes AnimatedGradient {
    0% {
        background-position: 0% 50%
    }
    50% {
        background-position: 100% 50%
    }
    100% {
        background-position: 0% 50%
    }
}

.animated-gradient {
    background: linear-gradient(270deg, #FC5C7D, #6A82FB, #EB3349, #F45C43, #FF8008, #FFC837, #4CB8C4, #3CD3AD, #24C6DC, #514A9D, #FF512F, #DD2476, #DA22FF, #9733EE, #22c1c3, #fdbb2d);
    background-size: 3200% 3200%;
    animation: AnimatedGradient 160s linear infinite;
}

body {
  text-align: center;
  margin: 0;
  padding: 0;
}

.btn {
  background-color: #000;
  color: #fff;
  padding: 10px;
  transition-duration: 0.4s;
  transition-timing-function: ease;
  border-top: solid 25px #fff;
  border-bottom: solid 25px #fff;
  border-left: solid 150px #fff;
  border-right: solid 150px #fff;
  margin-top: 50px;
}

.btn:hover {
  background-color: transparent;
  color: #fff;
  transition-duration: 0.4s;
  transition-timing-function: ease;
}
<html>
<body class="animated-gradient">
  <div>
    <button class="btn">Hover Me!</button>
  </div>
</body>
</html>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接