如何重写使用@for循环的SCSS Mixin

时间:2019-09-11 14:48:47

标签: sass scss-mixins

我需要有关scss mixin的帮助。我试图通过利用mixin中的for循环使用nth:child()选择器来添加动画延迟。每个孩子的延迟应以.5秒为增量增加。

li {
    list-style: none;
    transform: translateX(100rem);
    animation: slideIn .5s forwards;

    &:nth-child(1) {
      animation-delay: 0s;
    }

    &:nth-child(2) {
      animation-delay: .5s;
    }

    &:nth-child(3) {
      animation-delay: 1s;
    }

    &:nth-child(4) {
      animation-delay: 1.5s;
    }
}

我用mixin代替了原始的scss。请注意,上面的第一个孩子的动画延迟为0s。

@mixin delay {
    @for $i from 1 through 4 {
        &:nth-child(#{$i}) {
            animation-delay: $i * (0.5s);
        }
    }
}

最终代码。

li {
    list-style: none;
    transform: translateX(100rem);
    animation: slideIn .5s forwards;
    @include delay;
}

这很好,除了会延迟第一个孩子。我如何重写此混合,以便跳过第一个子节点并从第二个子节点开始?

1 个答案:

答案 0 :(得分:0)

您可以从2循环到4(就像@mfluehr所说的那样,因为默认情况下animation-delay是0 => https://www.w3schools.com/cssref/css3_pr_animation-delay.asp,因为),将($i - 1)添加到您的{{1} }。

所以,这可能是您的新混音:

animation-delay

您的输出:

@mixin delay {
    @for $i from 2 through 4 {
        &:nth-child(#{$i}) {
            animation-delay: ($i - 1) * (0.5s);
        }
    }
}

li {
    list-style: none;
    transform: translateX(100rem);
    animation: slideIn .5s forwards;
    @include delay;
}

我还添加了一个示例,其中包含不带li { list-style: none; transform: translateX(100rem); animation: slideIn 0.5s forwards; } li:nth-child(2) { animation-delay: 0.5s; } li:nth-child(3) { animation-delay: 1s; } li:nth-child(4) { animation-delay: 1.5s; } 的新CSS:

li:nth-child(1)
li {
  list-style: none;
  transform: translateX(100rem);
  animation: slideIn .5s forwards;
}
li:nth-child(2) {
  animation-delay: 0.5s;
}
li:nth-child(3) {
  animation-delay: 1s;
}
li:nth-child(4) {
  animation-delay: 1.5s;
}

@keyframes slideIn {
    100% { transform: translateX(0); }
}