less、scss 函数 ---for 循环变量生成样式

1,671 阅读1分钟

在项目开发时,我们通常需要生成一些通用的样式,如下,一个一个写,费时费力,还low。现在,就介绍less、scss 中,如何巧妙的运用函数来实现

.ml-5 {
  margin-left: 5px;
}
.ml-10 {
  margin-left: 10px;
}
.ml-15 {
  margin-left: 15px;
}
.ml-20 {
  margin-left: 20px;
}
.ml-25 {
  margin-left: 25px;
}
.ml-30 {
  margin-left: 30px;
}
.ml-35 {
  margin-left: 35px;
}

Less

可使each函数来遍历变量,如下

// 定义margin变量
@marginKey: 5, 10, 15, 20, 25, 30, 35; 
//循环变量生成
each(@marginKey, { 
.ml-@{value} { margin-left: @value*1px; }
})

对这种特殊的呈现等比倍数增加的样式,还有更简便的方法,如下,可使用range函数来生成遍历对象

each(range(7), { 
.ml-@{value} { margin-left: @value*5px; }
})

另外,对象遍历也是很常用的方法。

@set: { one: blue; two: green; three: red; } 
.set { each(@set,{ 
  @{key}-@{index}: @value; 
  });
}
// 输出
.set { one-1: blue; two-2: green; three-3: red; }
@colors: {
  0: #000;
  3: #333;
  6: #666;
};
each(@colors, {
   .col-@{key}{
    color: @value;
   }
});
//输出
.col-0{
    color:#000;
}
.col-3{
    color:#333;
}
.col-6{
    color:#666;
}

更多less函数,参考文档 less.bootcss.com/functions/

Scss

使用@each $i in循环

$marginKey: 5, 10, 15, 20, 25, 30, 35; 
@each $i in $marginKey{
    .ml-#{$i}{
      margin-left: $i * 1px;
    }
  }

或者使用@for $i from through 或者@for $i from to来循环变量, through 包含结束值 , to 不包含结束值

@for $i from 1 through 7{
    .ml-#{5 * $i}{
      margin-left: $i * 5px;
    }
  }

对象遍历。使用map-keysmap-values函数来获取键和值列表

$colors: (

    primary: #333,

    secondary: #666,

    tertiary: #999

);

// 枚举键

@each $key in map-keys($colors) {

    .text-#{$key} {

        color: map-get($colors, $key);

    }

}

// 枚举值

@each $value in map-values($colors) {

    [data-color="#{$value}"] {

        background-color: $value;

    }

}

更多scss函数,参考文档www.sass.hk/docs/