首页 > 解决方案 > CSS 动画不适用于 ::before 和 ::after

问题描述

我有这个来自互联网的心脏动画,div使用::before::after制作一个心形。

我已经对其进行了修改,因此我可以将颜色从红色更改为粉红色。问题是我无法更改动画的颜色::before::after使用thump动画。我添加了另一个动画来改变::before和的颜色::after。虽然重击可以缩放::before::after不能改变颜色。

thum应该改变和的::before颜色::after

.heart {
  width: 100px;
  height: 100px;
  background-color: pink;
  transform: rotate(-45deg);
  position: absolute;
  left: 100px;
  top: 100px;
  animation-name: thump;
  animation-duration: 2s;
  animation-iteration-count: infinite;
}

.heart::before {
  content: "";
  background-color: pink;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  position: absolute;
  bottom: 50px;
  animation-name: change-color;
  animation-duration: 2s;
  animation-iteration-count: infinite;
}

.heart::after {
  content: "";
  background-color: pink;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  position: absolute;
  left: 50px;
  animation-name: change-color;
  animation-duration: 2s;
  animation-iteration-count: infinite;
}

@keyframes thump {
  0% {
    transform: scale(1.2) rotate(-45deg);
    background-color: red;
  }
  100% {
    transform: scale(1) rotate(-45deg);
    background-color: pink;
  }
}

@keyframes change-color {
  0% {
    background-color: red;
  }
  100% {
    background-color: pink;
  }
}
<div class="heart"></div>

标签: csscss-animations

解决方案


我所做的只是摆脱了 div 和选择器中多余的背景颜色道具;在 thump 和 change-color 中交换颜色。如果这解决了你的问题。

为什么重击前后不改变背景颜色?

因为它不会干扰这两个,因为我们只对这些选择器使用改变颜色的动画。

.heart {
  width: 100px;
  height: 100px;
  transform: rotate(-45deg);
  position: absolute;
  left: 100px;
  top: 100px;
  animation: thump 2s infinite;
}

.heart::before {
  content: "";
  width: 100px;
  height: 100px;
  border-radius: 50%;
  position: absolute;
  bottom: 50px;
  animation: change-color 2s infinite;
}

.heart::after {
  content: "";
  width: 100px;
  height: 100px;
  border-radius: 50%;
  position: absolute;
  left: 50px;
  animation: change-color 2s infinite;
}

@keyframes thump {
  0% {
    transform: scale(1.2) rotate(-45deg);
    background-color:pink ;
  }
  100% {
    transform: scale(1) rotate(-45deg);
    background-color: red;
  }
}
@keyframes change-color{
  0% {
    background-color:pink ;
  }
  100% {
    background-color: red;
  }
<div class="heart"></div>


推荐阅读