【问题标题】:Triggering a transition mid-animation CSS触发过渡动画 CSS
【发布时间】:2020-05-07 10:50:33
【问题描述】:

尝试在使用 CSS 的运行动画中使用 :hover 触发过渡,在下面的示例中,:hover 上只有 background-color 更改,但 transform 属性仅在动画停止后触发。如何在动画期间触发transform: rotate

此外,当我重新加载页面时,我最初的background-color: red 似乎淡入了,而我没有通过:hover 明确触发它。我认为这是由transition-duration 引起的,仅使用 CSS 可以避免这种情况吗?

.container {
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.red {
  width: 100px;
  height: 100px;
  background-color: red;
  animation-name: animation;
  animation-duration: 5s;
  animation-delay: 0;
  animation-timing-function: ease-in-out;
  animation-direction: alternate;
  transition-duration: 5s;
  transition-property: all;
}

.red:hover {
  transform: rotate(180deg);
  background-color: teal;
}

@keyframes animation {
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.5);
  }

  100% {
    transform: scale(1);
  }
}
<body>
  <div class="container">
    <div class="red"></div>
  </div>
</body>

【问题讨论】:

    标签: html css css-animations css-transitions


    【解决方案1】:

    转换不会以这种方式堆叠。解决此限制的一种方法是使用父元素进行旋转变换。

    .container {
      height: 300px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .red {
      width: 100px;
      height: 100px;
      background-color: red;
      animation-name: animation;
      animation-duration: 5s;
      animation-delay: 0;
      animation-timing-function: ease-in-out;
      animation-direction: alternate;
      transition-duration: 5s;
      transition-property: all;
    }
    
    .red:hover {
      background-color: teal;
    }
    
    .wrap {
      transition: all 5s;
    }
    
    .wrap:hover {
      transform: rotate(180deg);
    }
    
    @keyframes animation {
      0% {
        transform: scale(1);
      }
    
      50% {
        transform: scale(1.5);
      }
    
      100% {
        transform: scale(1);
      }
    }
    <body>
      <div class="container">
        <div class="wrap">
          <div class="red"></div>
        </div>
        
      </div>
    </body>

    【讨论】:

    • 感谢您的回答,我在发布问题之前自己尝试了您的解决方案并且它有效,我只是想知道我是否可以在没有父元素的情况下做到这一点。
    • 加载页面时背景色淡入怎么办,我可以去掉它让.red div立即显示吗?
    • 我不相信在这种情况下有任何其他方式可以使用多个转换。我不确定“加载页面时背景颜色淡入”是什么意思。红色方块应该立即可见。
    • 我使用 chrome,当重新加载页面时,.red div 需要 5 秒才能慢慢出现在页面上,从不可见到完全可见,如果我删除了 transition-duration: 5s;然后它立即出现。但在这种情况下,当我从 .red div 中移除光标时,我失去了从蓝绿色到红色的缓慢过渡。
    • 这就是你在上面的例子中看到的?还是在您自己的网页上?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    • 2014-04-19
    • 1970-01-01
    • 2018-04-20
    • 2011-10-27
    • 2020-03-20
    • 2020-06-05
    相关资源
    最近更新 更多