【问题标题】:CSS refactoring animated divsCSS 重构动画 div
【发布时间】:2013-07-09 17:23:05
【问题描述】:

我有大量代码用于相对简单的事情,在 JSFiddle here 中找到一个简短的动画,但我对我编写的代码感到失望。我觉得它可能会,或者至少应该会短很多,因为我不得不重复自己做一些如此细微的不同的事情:

HTML:

<div class="movement">
    <div class="mover x1 back"></div>
    <div class="mover x2 front"></div>
    <div class="mover x3 back"></div>
    <div class="mover x4 front"></div>
    <div class="mover x5 back"></div>
    <div class="mover x6 front"></div>
</div>

CSS:

.mover {
    position: absolute; 
    width: 200px; 
    height: 20px;
    background: black;

    -webkit-animation: animato 18s linear infinite;
    -moz-animation: animato 18s linear infinite;
    -o-animation: animato 18s linear infinite;
    animation: animato 18s linear infinite;
}

...

.x1 {
    right: 30%;
    top: 90px;

    -webkit-animation-delay: -3s;
    -moz-animation-delay: -3s;
    -o-animation-delay: -3s;
    animation-delay: -3s;
}
.x2 {
    right: 45%;
    top: 130px;
    -webkit-transform: scale(0.6);
    -moz-transform: scale(0.6);
    -o-transform: scale(0.6);
    transform: scale(0.6);
    opacity: 0.6; 

    -webkit-animation-delay: -6s; 
    -moz-animation-delay: -6s;
    -o-animation-delay: -6s;
    animation-delay: -6s;
}

... for each and every moving object, up to x6

我真正想做的是只有一个容器 div(上面的 HTML 中的 class="movement")没有子 div 标签,我可以在其中创建 6 个滚动的移动对象。此外,不必重复 -vendor-animation-delay 或 -vendor-transform 只是为了更改每个规则的延迟时间/比例,这将是非常棒的。有没有更好的代码重构我错过了,还是我真的必须在每个 div 上重复这个以使用 CSS 实现这种效果?

【问题讨论】:

    标签: html css css-animations


    【解决方案1】:

    除了使用 Sassless 之类的预处理器,您无能为力,它可以让您缩短 css(sass 示例):

    @mixin prefixes($declaration,$value){
        -webkit-#{$declaration}:$value;
        -moz-#{$declaration}:$value;
        -o-#{$declaration}:$value;
        #{$declaration}:$value;
    }
    @mixin animation-delay($delay){
        @include prefixes("animation-delay",$delay);
    }
    @mixin position($right,$top){
        right:$right;
        top:$top;
    }
    .x1 {
        @include position(30%,90px);
        @include animation-delay(-3s);
    }
    .x2 {
        @include position(45%,130px);
        @include animation-delay(-6s);
        /* same is possible for the transform, etc. */
    }
    

    我会在小提琴中向您展示一个示例(实际上您可以在那里使用 sass:语言 -> 切换 CSS -> SCSS)但不幸的是,sass 选项似乎被破坏了。

    less/sass 源代码肯定更容易维护,但最终它会编译为您原来的冗长 CSS。

    【讨论】:

    • 我对 SO 的了解越多,我就越发现 OOCSS 与 CSS 相比更加通用。这是一个更易于管理的替代方案 - 谢谢。
    【解决方案2】:

    看看Animate.css

    引自 Animate.css 网站:

    animate.css 是一组很酷、有趣且跨浏览器的动画,供您在项目中使用。非常适合强调、主页、滑块和一般的加水效果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 2014-10-29
      • 1970-01-01
      • 2017-08-28
      相关资源
      最近更新 更多