【问题标题】:sass if even number in for loopsass if for 循环中的偶数
【发布时间】:2015-02-23 06:15:00
【问题描述】:

我正在尝试做一些非常简单的事情,但似乎做不到,这让我发疯。我想知道我的数字是否是偶数,并将变量加一。这是我一直在尝试的:

@for $i from 1 through 6 {
    $rgba-opacity:0.5;
    &:nth-child(#{$i}) {
        background: rgba($color-white-primary, $rgba-opacity);
    }
    @if #{$i} % 2 == 0 {
        $rgba-opacity: $rgba-opacity+0.5;
    }
}

基本上我想做的是孩子一和二,得到一个颜色值,孩子三和四得到另一个,孩子五和六得到第三个。关于为什么这不起作用的任何想法?非常感谢您的帮助。

【问题讨论】:

    标签: for-loop sass increment


    【解决方案1】:

    在你的代码中(假设你已经粘贴了完整的代码),你直接使用&:nth-child()会报错Base-level rules cannot contain the parent-selector-referencing character '&'.你需要为它指定一个父选择器。

    $r : 100;
    $g : 120;
    $b : 140;
    $rgba-opacity:0.5;
    
    @for $i from 1 through 6 {  
      div {
        &:nth-child(#{$i}) {
         background: rgba($r, $g, $b, $rgba-opacity);
         &:before {
          content: ""+$i;
         }
        }
      }
      @if $i % 2 == 0 {  //use $i for calculating mod here than #{$i}
       $rgba-opacity: $rgba-opacity + 0.2;
       $r: $r + 100;
       $g: $g + 100;
      }
    }
    

    HTML

    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    

    输出:

    Demo here

    【讨论】:

    • 非常感谢您花时间解释这一点,我真的很感激。只是学习这一点,有时你只需要解释一下或解释一下。
    猜你喜欢
    • 1970-01-01
    • 2021-10-08
    • 2021-07-30
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多