3

试图在transformkeyframes. 假设我有以下内容:

HTML

<div id="box"></div>

CSS

#box {
    width:300px;
    height:300px;
    background-color:red;

    animation: animate 5s;
    animation-iteration-count: infinite;
    animation-direction: alternate;
    animation-timing-function: ease-in-out;
}
@keyframes animate {
    from {
        transform: scale(0.8) translateY(100px) rotate(10deg);
    }
    to {
        transform: scale(0.8) translateY(100px) rotate(-10deg);
    }
}

JSFiddle 示例

如何防止在动画中执行scale(0.8)and ?translateY(100px)我只希望它来回旋转,而不必在每个步骤的变换中应用这些属性。这里只使用了两个步骤(fromto),但是如果使用多个步骤(例如使用0%, 20%, 40%, 60%, 80%, 100%)则意味着很多重复的代码。正如您可以想象的那样,当稍后出现更改时,这并不是很好。

最终,我正在寻找这样的东西(这是不可能的,因为该transform属性将被覆盖):

#box {
    transform: scale(0.8) translateY(100px);
}

@keyframes animate {
    from {
        transform: rotate(10deg);
    }
    to {
        transform: rotate(-10deg);
    }
}

这甚至可能吗?

附言。我不是在寻找将width/更改heightscale和/或将margin/top属性更改为的答案translate。LESS/SASS 也没有任何东西可以使值易于更改,因为它仍然会导致重复的代码。

4

2 回答 2

3

我为您整理了两个选项-jsFiddle

选项 1 - 不是 DRY,而是更浓缩一点:

 #box {
        width:300px;
        height:300px;
        background:red;
        animation: animate 1s ease-in-out 0s infinite alternate;
    }
    @keyframes animate {
        from {
            transform: scale(0.8) translateY(100px) rotate(10deg);
        }
        to {
            transform: scale(0.8) translateY(100px) rotate(-10deg);
        }
    }

选项 2 - 技术上干燥,但不一定“更好”

<div id="option2">
    <div id="box2"></div>
</div>

#option2{
    transform: scale(0.8) translateY(100px);
}
#box2 {
    width:300px;
    height:300px;
    background-color:blue;
    animation: animate2 6s ease-in-out 0s infinite alternate;
}
@keyframes animate2 {
    0%, 40%, 80% {
        transform: rotate(10deg);
    }
    20%, 60%, 100% {
        transform: rotate(-10deg);
    }
}

我猜想使用选项 2 可能是值得的,如果您使用的是更复杂的动画,但我不确定是否只是将它包装在一个包含div和缩放/翻译包含div将提供任何真正的好处小规模。

于 2013-05-07T14:58:55.007 回答
0

哇,所以我认为肯定有一种方法可以做到这一点,而不必为每个关键帧动画重新​​编写 scale 和 translateY 属性。我尝试了几种不同的方法,但无法获得您想要的结果。如果参数是新的,则似乎 transform 应该能够接受更多参数而不会覆盖旧参数。

我知道您说过您不想使用 LESS/SASS,因为它在技术上并不干燥,但如果您希望在一个地方编写代码并在任何地方进行更新,我会建议您这样做。我认为它是干的,因为你没有重复自己(即使代码是)。我想不出任何其他方法来得到你想要的。

于 2013-04-12T15:40:42.877 回答