首页 > 解决方案 > 我在使用 css3 动画方向时遇到问题

问题描述

各位开发者您好,

我正在尝试使用 CSS3 动画在 Z 轴上构建旋转

HTML
///

<div>
<div id="rotZ" class = "square">ROTATE</div>
</div>

CSS
///
div {
    perspective: 500px; 
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

.square {
    width: 200px;
    height: 200px;
    background: grey;
    animation: rotateAnimation 4s linear infinite;
}

@keyframes rotateAnimation {
    from {transform: rotateZ(0deg);}
    to {transform: rotateZ(360deg);}
}


JS
///
var direction = 'normal';

var d = document.getElementById('rotZ');

d.addEventListener('click', changeDir);

function changeDir() {
    direction = direction == 'normal' ? 'reverse' : 'normal';
    
    d.style.animationDirection = direction;
}

就像在这个codepen https://codepen.io/pdelia/pen/QWpZvOr

我想要的是在单击 div 时来回反转动画。

代码有效,但 div 的 rotationZ 值正在改变,所以我无法实现我需要的。

我尝试使用 getComputedStyle() 以度为单位获取 rotateZ 值(因此我可以相应地更改关键帧),但它返回的是一个 matrix3d 对象,而我试图转换为度数的任何东西都失败了。stackoverflow 中的相关帖子,例如使用 JavaScript 从 matrix3d() 获取 3D CSS 旋转值和从 matrix3d获取准确的旋转角度不返回有效值。

我可以做些什么来改变特定 Z 值的旋转方向,使动画看起来平滑吗?

标签: javascriptcssanimation

解决方案


推荐阅读