首页 > 解决方案 > CSS:在另一个动画期间更改div的颜色

问题描述

我想在另一个 div 执行动画时更改 div 的颜色。我已经准备好我的 html 文件:

   .body {
      width: 1200px;
      background-color: white;
      font-family: sans-serif;
      font-size: 20px;
      margin: 50px;
    }

    .bar {
      stroke: black;
      stroke-width: 0.1;
      background-color: cornflowerblue;
      width: 500px;
      height: 25px;
      left: 100px;
      top: 100px;
      position: absolute;
      animation-name: expandBar;
      animation-duration: 2s;
      animation-delay: 1s;
      animation-fill-mode: both;
      transition-timing-function: ease-in-out;
    }
    @keyframes expandBar {
      from {
          width: 0px;
      }
      to {
          width: width;
      }
    }

    .box {
      stroke: black;
      stroke-width: 0.1;
      background-color: cornflowerblue;
      width: 100px;
      height: 100px;
      left: 100px;
      top: 135px;
      position: absolute;
    }
    <html lang="de">
      <head>
        <meta charset="utf-8" />
        <title>Title</title>
        <link rel="stylesheet" href="bc.css" />
      </head>

      <body>
        <div class="bar"></div>
        <div class="box"></div>
      </body>
    </html>


 

对于初学者,我尝试使用以下代码来测试它是如何工作的(我在互联网上看到过)。工作正常。

.bar:hover ~ .box{
  background-color: red;
}

但是,我现在不知道如何处理 bar 元素的动画。我希望在条形图展开的 2 秒内该框为红色。

有没有可以用来代替悬停的关键字?还是有其他方法可以做到这一点?

标签: htmlcsscss-animations

解决方案


我不能直接想到只使用 CSS 的解决方案。但是一点 javascript 可能会有所帮助。有onanimationstartonanimationend这可能会帮助你。链接到 MDN 文档

下面是一个工作示例。

let bar = document.getElementById("bar")
let box = document.getElementById("box")

bar.onanimationstart = function(event){
  box.classList.add("red")
}

bar.onanimationend = function(event){
  box.classList.remove("red")
}
#body {
  width: 1200px;
  background-color: white;
  font-family: sans-serif;
  font-size: 20px;
  margin: 50px;
}

#bar {
  stroke: black;
  stroke-width: 0.1;
  background-color: cornflowerblue;
  width: 500px;
  height: 25px;
  left: 100px;
  top: 100px;
  position: absolute;
  animation-name: expandBar;
  animation-duration: 2s;
  animation-delay: 1s;
  animation-fill-mode: both;
  transition-timing-function: ease-in-out;
}
@keyframes expandBar {
  from {
      width: 0px;
  }
  to {
      width: width;
  }
}

#box {
  stroke: black;
  stroke-width: 0.1;
  background-color: cornflowerblue;
  width: 100px;
  height: 100px;
  left: 100px;
  top: 135px;
  position: absolute;
}

.red{
  background-color: red !important;
}
<!DOCTYPE html>

<html lang="de">
  <head>
    <meta charset="utf-8" />
    <title>Title</title>
    <link rel="stylesheet" href="bc.css" />
  </head>

  <body>
    <div id="bar"></div>
    <div id="box"></div>
  </body>
</html>


推荐阅读