【问题标题】:Dont reset transformation when launching a new animation with CSS使用 CSS 启动新动画时不要重置转换
【发布时间】:2022-01-26 09:50:16
【问题描述】:

小提琴:https://jsfiddle.net/7p9uv16b/

我有几个块在开始时以不同的角度旋转。我想在点击时沿旋转轴平移它们。但是平移动画会重置旋转角度。我知道我可以将转换链接到旋转 + 平移,但我需要多个动画(每个块一个)。 CSS 是否提供了一种方法来保持当前状态作为新转换的参考?

HTML:

<button type="button" onclick="move()">
  Animate blocks
</button>
<button type="button" onclick="reset()">
  Reset
</button>
<div id="s1" class="square">
</div>
<div id="s2" class="square">
</div>

CSS:

.square{
  height: 50px;
  width: 50px;
  background-color: #58ACFA;
  margin: 100px;
}

.move{
   -webkit-animation: move 2s  both;
             animation: move 2s  both;
}

@-webkit-keyframes move {
  0% {
    -webkit-transform: translateX(0);
            transform: translateX(0);
  }
  100% {
    -webkit-transform: translateX(100px);
            transform: translateX(100px);
  }
}
@keyframes move {
  0% {
    -webkit-transform: translateX(0);
            transform: translateX(0);
  }
  100% {
    -webkit-transform: translateX(100px);
            transform: translateX(100px);
  }
}

Javascript:


$('#s1').css('transform','rotate(45deg)');
$('#s2').css('transform','rotate(30deg)');

function move(){
    $('.square').addClass('move');
}

function reset(){
    $('.square').removeClass('move');
}

【问题讨论】:

    标签: javascript css animation css-animations


    【解决方案1】:

    您可以使用 CSS 变量。

    .square {
      --position: 0px;
      --angle: 0deg;
    
      -webkit-transform: translateX(var(--position)) rotate(var(--angle));
              transform: translateX(var(--position)) rotate(var(--angle));
    }
    
    #s1 {
      --angle: 45deg;
    }
    
    #s2 {
      --angle: 30deg;
    }
    
    @keyframes move {
      0% {
        --position: 0px;
      }
      100% {
        --position: 100px;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-09
      • 1970-01-01
      • 2019-11-26
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      相关资源
      最近更新 更多