【问题标题】:How do I rewrite this SCSS Mixin that uses a @for loop如何重写这个使用 @for 循环的 SCSS Mixin
【发布时间】:2019-09-11 14:48:47
【问题描述】:

我需要有关 scss mixin 的帮助。我正在尝试通过在 mixin 中使用 for 循环来使用 nth:child() 选择器添加动画延迟。每个孩子的延迟应该以 0.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;
}

这很好用,只是它给第一个孩子增加了延迟。我该如何重写这个 mixin,让它跳过第一个孩子并从第二个孩子开始?

【问题讨论】:

  • @for $i from 2 through 4
  • 我试过了,但它没有按预期执行。它只是给第二个孩子增加了更长的延迟。

标签: sass scss-mixins


【解决方案1】:

您可以从 2 循环到 4(正如 @mfluehr 所说,他的评论是因为默认情况下 animation-delay 是 0 => https://www.w3schools.com/cssref/css3_pr_animation-delay.asp),将 ($i - 1) 添加到您的 animation-delay

所以,这可能是你的新 mixin:

@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;
}

我还添加了一个没有 li:nth-child(1) 的新 CSS 示例:

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); }
}
<ul>
	<li>1</li>
	<li>2</li>
	<li>3</li>
	<li>4</li>
</ul>

【讨论】:

  • 这成功了!当我尝试循环 2 到 4 时,我没有包括 ($i - 1)。你愿意帮我理解那行代码吗?我想我不明白为什么在指定 2 到 4 时需要添加该部分。
  • 当然。因为您希望第二个 li 以 0.5s 没有 1s (2*0,5 = 1) 的延迟开始。为此,我们必须在每个循环中删除一个 $i 单位(2-1=1 然后 1*0.5=0.5;3-1=2 然后 2*0,5=1;4-1=3 然后 3 *0,5 = 1,5...)
  • 这是有道理的。只需要一些练习就可以理解它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
  • 2017-05-05
  • 1970-01-01
  • 1970-01-01
  • 2020-03-05
相关资源
最近更新 更多