Sass @each规则用法解析和示例

2021年3月31日17:58:02 发表评论 1,113 次浏览

each@规则用于为列表的每个元素或Map的每个对发出样式或评估代码。重复其中有一些差异的样式最有利。对于已分配给提供的变量名称的列表或映射对中的每个元素, 评估该部分。

语法如下:

@each <variable> in <expression> {
    ... 
}

例子:

$sizes: 20px , 30px , 100px ;
@each $size in $sizes {
   .gfg-#{$size} {
     font-size : $size;
     height : $size;
     width : $size;
   }
}

输出如下: 

.gfg-20px {
  font-size: 20px;
  height: 20px;
  width: 20px;
}

.gfg-30px {
  font-size: 30px;
  height: 30px;
  width: 30px;
}

.gfg-100px {
  font-size: 100px;
  height: 100px;
  width: 100px;
}

@each通过遍历Map的每个键/值对, 规则也可以用于Map。

语法如下:

@each <variable>, <variable> in <expression> { 
    ... 
}

例子:在此示例中, 键被分配给第一个变量名称, 元素被分配给第二个变量名称。

$colors: ( arial : black , sans-serif : green , algerian: gray );
  
@each $name, $font in $colors {
   .font-#{$name}:before {
     background-color : white ;
     font-family : $name;
     color : $font;
   }
}

输出如下: 

.font-arial:before {
  background-color: white;
  font-family: arial;
  color: black;
}

.font-sans-serif:before {
  background-color: white;
  font-family: sans-serif;
  color: green;
}

.font-algerian:before {
  background-color: white;
  font-family: algerian;
  color: gray;
}

销毁:@each规则还可以自动将列表列表中的变量分配给内部列表中的每个值。由于变量与内部列表的结构匹配, 因此称为解构。每个变量名称都分配给列表中其对应位置的值;如果列表中没有足够的值, 则将其分配为null。

语法如下:

@each <variables...> in <expression> {  
    ... 
}

例子:在此示例中, 键被分配给第一个变量名称, 元素被分配给第二个变量名称。

$colors: 
   arial black 10px , sans-serif green 12px , algerian gray 20px ;
  
@each $name, $font, $size in $colors {
   .font-#{$name}:before {
     background-color : white ;
     font-family : $name;
     color : $font;
     font-size : $size;
   }
}

输出如下:

.font-arial:before {
  background-color: white;
  font-family: arial;
  color: black;
  font-size: 10px;
}

.font-sans-serif:before {
  background-color: white;
  font-family: sans-serif;
  color: green;
  font-size: 12px;
}

.font-algerian:before {
  background-color: white;
  font-family: algerian;
  color: gray;
  font-size: 20px;
}

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: