Writing a loop that increments by a value other th

2019-01-14 15:52发布

问题:

In SASS, a loop is written like so:

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

This would yield 1, 2, 3, 4... all the way to 100.

How would you make the loop go in intervals of two units?

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

So the result is 1, 3, 5, 7... to 99

回答1:

It isn't in the documentation because it simply isn't implemented. What you want to do can be done with the @while directive.

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


回答2:

Sass does not provide a way to specify how much to increment using @for loops. Instead, you write your loop to reflect how many steps you need to take to get your final output. For all of the odd numbers from 1 through 100, that's 50 steps (100 / 2). Inside the loop, you use arithmetic (addition, subtraction, multiplication, division) to arrive at your final value.

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

DEMO

or a bit more general version:

$max: 100;
$step: 2;

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

DEMO



回答3:

I'd use Modulus for this. The Modulus operator gives you the remainder of the division of a number into another number. E.g (3 % 2) will give you 1, as will (5 % 2) or (7 % 2).

If you used this:

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

You'll get 2,4,6,8,10...100

But you want 1,3,5,7,9...99 – so offset it by 1:

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


回答4:

Other example more:

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


标签: sass