编写一个循环,该循环在Sass中以非1的值递增

ass CSS

十三

2020-03-20

在SASS中,这样编写一个循环:

@for $i from 1 through 100 {
    //stuff
}

这将产生1,2,3,4 ...一直到100。

您如何使循环以两个单位的间隔进行?

@for $i from 1 through 100 *step 2*{
    //stuff
}

所以结果是1,3,5,7 ...到99

第2507篇《编写一个循环,该循环在Sass中以非1的值递增》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
路易EvaSam 2020.03.20

Sass没有提供使用@for循环指定增量的方法。相反,您编写循环以反映获得最终输出所需执行的步骤。对于从1到100的所有奇数,即50步(100/2)。在循环内部,您可以使用算术(加法,减法,乘法,除法)得出最终值。

@for $i from 1 through 50 {
  $value: $i * 2 - 1;
  // stuff
}

演示

或更通用的版本:

$max: 100;
$step: 2;

@for $i from 1 through ceil($max/$step) {
  $value: ($i - 1)*$step + 1;
  // stuff
}

演示

伽罗理查德 2020.03.20

其他示例更多:

.my-class {
    $step    : 5;
    $from    : ceil( 1 /$step);
    $through : ceil( 100 /$step);
    $unit    : '%';

    @for $i from $from through $through {
      $i : $i * $step;
      width: $i#{$unit};
    }
}
卡卡西Near 2020.03.20

我会为此使用Modulus。模运算符可为您提供数字除法的余数。例如(3%2)会给您1,(5%2)或(7%2)。

如果您使用此方法:

@for $i from 1 through 100 {
    @if $i % 2 == 0 {
        #{$i}
    }
}

您将获得2,4,6,8,10 ... 100

但是您想要1,3,5,7,9 ... 99 –因此将其偏移1:

@for $i from 1 through 100 {
    @if ($i+1) % 2 == 0 {
        .your-class-#{$i} {
          // do stuff
        }
    }
}
Stafan路易 2020.03.20

它不在文档中,因为它根本没有实现。您可以使用该@while指令完成操作

$i: 1;
@while $i < 100 {
  // do stuff
  $i: $i + 2;
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android