简体   繁体   English

如何在 CSS 中的旋转元素上使用 animation

[英]How to use animation on a rotated element in CSS

I have an div element that is rotated 90 degree by default.我有一个默认旋转 90 度的 div 元素。 Now I want to apply animation effect on it on click.现在我想在点击时对其应用 animation 效果。 Is there a way to preserve the rotation effect throughout the life of animation?有没有办法在 animation 的整个生命周期中保持旋转效果?

When I use animation, I was able to define the CSS effect on 0%, 50%, and 100% of the life of animation.当我使用 animation 时,我能够定义 CSS 对 animation 寿命的 0%、50% 和 100% 的影响。 But the element has a random chance of rotating 90 or -90 degrees, I cannot put a hardcoded rotation within the keyframes definition.但是该元素有随机旋转 90 度或 -90 度的机会,我不能在关键帧定义中放置硬编码旋转。

<div class="solid clock ani">&#10004;</div>
<div class="solid counterclock ani">&#10004;</div>
.solid {width:50px; height:50px}
.clock {transform: rotate(90deg)} /*clock-wise rotation*/
.counterclock {transform: rotate(-90deg)} /*counter-clock-wise rotation*/
.ani {animation popit 0.2s linear 1 forwards} /*does not preserve rotation!!*/

@keyframes popit{
    0% {
      width: 0%;
      height: 0%;
      opacity: 0;
      border-radius: 50%;
    }
    50% {
      width: 150%;
      height: 150%;
      transform: translateX(-10%);
      border-radius: 50%;
      opacity: 1;
    }
    100% {
      width: 100%;
      height: 100%;
      opacity: 1;
    }
  }

I would like to see if there is a way to dynamically add the rotation into the keyframes css definition above我想看看是否有办法将旋转动态添加到上面的关键帧 css 定义中

With the code above, the element would rotate back to the original position, apply the animation and then rotate 90deg.使用上面的代码,元素将旋转回原来的 position,应用 animation,然后旋转 90 度。

Ideally I want the element to stay rotated throughout the life of the animation.理想情况下,我希望元件在 animation 的整个生命周期内保持旋转。

Consider CSS variable to append the rotation inside the animation:考虑 CSS 变量到 append animation 内部的旋转:

 .solid { width: 50px; height: 50px; display:inline-block; border:1px solid red; }.clock { transform: rotate(90deg); --d:90deg; } /*clock-wise rotation*/.counterclock { transform: rotate(-90deg); --d:-90deg; } /*counter-clock-wise rotation*/.ani { animation: popit 5s linear 1 forwards; } /*does not preserve rotation:;*/ @keyframes popit { 0% { opacity: 0; border-radius: 50%, } 50% { transform; translateX(-10%) rotate(var(--d:0deg)); border-radius: 50%; opacity: 1; } 100% { opacity: 1; } }
 <div class="solid clock ani">&#10004;</div> <div class="solid counterclock ani">&#10004;</div>

CSS animation property shorthand-syntax: CSS animation 属性简写语法:

animation: name duration timing-function delay iteration-count direction fill-mode play-state;

So in your case, you can define it as:因此,在您的情况下,您可以将其定义为:

animation: popit 5s linear infinite forwards;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM