html - CSS重构动画div

标签 html css css-animations

我有大量代码用于一些相对简单的东西,一个在 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 实现此效果?

最佳答案

除了使用像 Sass 这样的预处理器之外,您无能为力。或 less ,它允许您缩短您的 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. */
}

我会在 fiddle 中向您展示一个示例(实际上您可以在那里使用 sass:Languages -> switch CSS -> SCSS)但不幸的是,sass 选项似乎已损坏。

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

关于html - CSS重构动画div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17543763/

相关文章:

javascript - 显示/隐藏 Div 仅由按钮触发

html - 如何使 iFrame 中的 DIV 对齐?

css - Bootstrap 3 工具提示被包裹在每个空白处?

SVG CSS 动画不一致

javascript - 如何使列表平滑过渡

asp.net - 删除 HTML 或 ASPX 扩展

html - 2 种不同的链接样式在 IE 中显示正常,但在其他浏览器中显示不正确。单击链接时,所有链接都显示已访问

html - 图片上方的文字 CSS Z-Index 不起作用

CSS:悬停时关键帧动画消失

html - HTML 打印问题