Sass提供了接受参数的函数和混合器。你可以使用Sass的默认参数,也就是说,即使你在调用函数或混合器时没有提供参数,这些参数也有一个值。
让我们在这里集中讨论mixins。这里是mixin的语法。
@mixin foo($a, $b, $c) {
// I can use $a, $b, and $c in here, but there is a risk they are null
}
.el {
@include foo(1, 2, 3);
// if I tried to do `@include foo;`
// ... which is valid syntax...
// I'd get `Error: Missing argument $a.` from Sass
}
在这个Sass mixin中设置默认参数更安全、更有用。
@mixin foo($a: 1, $b: 2, $c: 3) {
}
.el {
// Now this is fine
@include foo;
// AND I can send in params as well
@include foo("three", "little", "pigs");
}
但如果我想送入$b 和$c ,但让$a 作为Sass的默认参数呢?诀窍是,你送入命名的参数。
@mixin foo($a: 1, $b: 2, $c: 3) {
}
.el {
// Only sending in the second two params, $a will be the default.
@include foo($b: 2, $c: 3);
}
一个使用Sass默认参数的现实生活中的例子
这里有一个快速混合器,可以输出你所需要的非常基本的风格化滚动条(Kitty也有一个)。
@mixin scrollbars(
$size: 10px,
$foreground-color: #eee,
$background-color: #333
) {
// For Google Chrome
&::-webkit-scrollbar {
width: $size;
height: $size;
}
&::-webkit-scrollbar-thumb {
background: $foreground-color;
}
&::-webkit-scrollbar-track {
background: $background-color;
}
// Standard version (Firefox only for now)
scrollbar-color: $foreground-color $background-color;
}
现在我可以这样调用它。
.scrollable {
@include scrollbars;
}
.thick-but-otherwise-default-scrollable {
// I can skip $b and $c because they are second and third
@include scrollbars(30px);
}
.custom-colors-scrollable {
// I can skip the first param if all the others are named.
@include scrollbars($foreground-color: orange, $background-color: black);
}
.totally-custom-scrollable {
@include scrollbars(20px, red, black);
}
我只是注意到这一点,因为我不得不四处搜索以弄清这一点。我正在尝试发送空字符串或null 作为第一个参数,以便 "跳过 "它,但这不起作用。必须采用命名参数的方法。