首页 > 解决方案 > 如何在已经由前向动画处理的元素上应用悬停效果?

问题描述

我在 SVG 元素的动画中有一个文本和块。在我的示例中,我简化了所有内容。

我想有一个初始动画,然后在块元素上悬停动画。初始动画效果很好。(使用 chrome 进行等于测量)。但是在初始动画之后,用户应该能够悬停块并且块本身应该调整大小(这也已经工作)并且文本应该得到不透明度1。但这不起作用,因为不透明度已经由关键帧动画。

关于如何解决这个问题的任何建议?我不介意我使用 JS 或 CSS 或任何框架。我不依赖 CSS 动画。只是使用它们,因为我认为我会更清洁。

重要编辑:我忘记了一件简单但非常重要的事情。在动画之前,还有一些关于不同元素的其他动画。所以我有一个延迟,比如说 2 秒。在动画开始之前,不透明度应该为 0,因此在动画开始之前文本是不可见的。对不起,忘记了!

.text{
  font-weight: bold;
  opacity: 0;
  transition: all .8s;
  animation: showText 3s ease-in-out forwards;
  animation-delay: 2s;
}

.text:hover{
  opacity: 1;
  transition: all .8s;
}

.block{
  top: 50px;
  left: 50px;
  position: absolute;
  height: 20px;
  width: 20px;
  background-color: red;
  transition: all .8s;
  animation: popup 3s ease-in-out;
  animation-delay: 2s;
}

.block:hover{
  transform: scale(2);
  transition: all .8s;
}

@keyframes showText {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.3;
  }
}

@keyframes popup {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(2);
  }
  100% {
    transform: scale(1);
  }
}
<div class='text'>
  Foo Bar!
</div>
<div class='block'>
</div>

codepen.io 链接(与上面相同的代码):https ://codepen.io/jdickel/pen/xJbQrY

标签: javascripthtmlcssanimationcss-animations

解决方案


forwards您可以简单地将初始不透明度设置为 ,而不是动画0.3

编辑:我相当有信心不能轻易覆盖正向动画样式(尽管由于某种原因我无法在文档中找到它),因此您可以按照最初的建议进行类似的操作,只需延长像这样的动画:

.text{
  font-weight: bold;
  /* Start out at 0.3 */
  opacity: 0.3;
  transition: all .8s;
  /* 2s + 3s = 5s */
  animation: showText 5s ease-in-out; /* no forwards */
}

.text:hover{
  opacity: 1;
  transition: all .8s;
}

.block{
  top: 50px;
  left: 50px;
  position: absolute;
  height: 20px;
  width: 20px;
  background-color: red;
  transition: all .8s;
  animation: popup 3s ease-in-out;
}

.block:hover{
  transform: scale(2);
  transition: all .8s;
}

@keyframes showText {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 0;
  }
  /* Note the new animation keyframe locations */
  70% {
    opacity: 1;
  }
  100% {
    opacity: 0.3;
  }
}

@keyframes popup {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(2);
  }
  100% {
    transform: scale(1);
  }
}
<div class='text'>
  Foo Bar!
</div>
<div class='block'>
</div>


推荐阅读