首先,您给出的 mixin 是 created by seven-phases-max 来模仿 for 和 for-each 循环,因为 Less 没有内置函数。与 Less 不同的是,Sass 已经内置了 @for 和 @each 指令来执行循环,因此我建议您不要花时间将这些 Less 混入转换为 Sass。
以下是 for 和 for-each 循环的 Sass 示例:
适用于:
.column {
@for $i from 1 through 5 { /* execute the loop 5 times */
&-#{$i} { /* create .column-1 to .column-5 using selector interpolation */
width: 20%;
left: (($i - 1) / 5 * 100%);
}
}
}
每个人:
$country-code-list: US, IN, FR, SG; /* list for iteration */
.flag {
@each $country-code in $country-code-list { /* iterate for each value in the list */
&-#{$country-code} { /* create .flag-US, .flag-IN etc using selector interpolation */
background-image: url(http://yoursite.com/#{$country-code}.png);
}
}
}
您可以尝试以上示例@SassMeister.com 并查看编译后的输出。
现在来回答你的问题,
1) 如何在 sass 中翻译守卫?在一个 mixin 中收集具有相同数量参数的 mixin 并在其中写入条件块是否正确?
Less 守卫将在 Sass 中转换为 @if(条件语句)。下面是一个例子:
@mixin list-style($val) {
@if ($val == i) { list-style-type: lower-roman; }
@else if ($val == I) { list-style-type: upper-roman; }
@else { list-style-type: decimal };
}
#demo { @include list-style(2); }
您问题的第二部分可能是基于意见的,因为每个人都有自己的做事方式。我个人更喜欢将它们分组到一个 mixin 中并编写条件块。
2) when(default()) 是如何工作的?
Less 中的default() 守卫类似于典型的else 或default:(在switch-case 中)语句。仅当没有其他具有相同名称和相同编号的 mixin 时,才会调用以 this 作为保护的 mixin。的参数匹配。
例如,看看下面的代码。这里,当作为参数传递给 mixin 的值不是 i 或 I 时,前两个 mixin 守卫都不匹配,因此这些 mixin 不会被执行。在这种情况下,第三个(default())将被执行并将列表样式类型设置为decimal。
.mixin-list-style(@val) when (@val = i) { list-style-type: lower-roman; }
.mixin-list-style(@val) when (@val = I) { list-style-type: upper-roman; }
.mixin-list-style(@val) when (default()) { list-style-type: decimal; }
#demo {
.mixin-list-style(1); /* this will result in list-style-type: decimal */
}
3) sass中有没有相当于less extract的函数?
是的,Sass 中有一个nth() 函数,它等效于Less extract() 函数。下面是一个示例:
$country-code-list: US, IN, FR, SG;
.flag-FR {
$country-code: nth($country-code-list, 3); /* extract 3rd item from country-code-list */
background-image: url(http://yoursite.com/#{$country-code}.png);
}
注意:@each 循环不需要这个,因为 Sass 会自动提取项目并为每次迭代分配给变量。