Sass 提供了接受参数的函数和mixin。您可以使用 Sass 默认参数,即即使在调用函数或 mixin 时不提供值,参数也具有值。
让我们关注 mixin。这是 mixin 的语法:
<code>@mixin foo($a, $b, $c) { // 我可以在此处使用 $a、$b 和 $c,但存在它们为空的风险 } .el { @include foo(1, 2, 3); // 如果我尝试执行 `@include foo;` // ... 这也是有效的语法... // 我会从 Sass 获取 `Error: Missing argument $a.` 错误 }</code>
在 Sass mixin 中设置默认参数更安全也更有用:
<code>@mixin foo($a: 1, $b: 2, $c: 3) { } .el { // 现在这样就可以了 @include foo; // 我也可以传入参数 @include foo("three", "little", "pigs"); }</code>
但是,如果我想传入 $b 和 $c,但将 $a 保留为 Sass 默认参数怎么办?诀窍是传入命名参数:
<code>@mixin foo($a: 1, $b: 2, $c: 3) { } .el { // 只传入第二个和第三个参数,$a 将为默认值。 @include foo($b: 2, $c: 3); }</code>
这是一个快速 mixin,它输出非常基本的样式化滚动条所需的内容(Kitty 也具有一个):
<code>@mixin scrollbars( $size: 10px, $foreground-color: #eee, $background-color: #333 ) { // 适用于 Google Chrome &::-webkit-scrollbar { width: $size; height: $size; } &::-webkit-scrollbar-thumb { background: $foreground-color; } &::-webkit-scrollbar-track { background: $background-color; } // 标准版本(目前仅适用于 Firefox) scrollbar-color: $foreground-color $background-color; }</code>
现在我可以像这样调用它:
<code>.scrollable { @include scrollbars; } .thick-but-otherwise-default-scrollable { // 我可以跳过 $b 和 $c,因为它们是第二个和第三个参数 @include scrollbars(30px); } .custom-colors-scrollable { // 如果所有其他参数都是命名的,我可以跳过第一个参数。 @include scrollbars($foreground-color: orange, $background-color: black); } .totally-custom-scrollable { @include scrollbars(20px, red, black); }</code>
我只是注意到这一点,因为我不得不四处搜索才能弄清楚这一点。我尝试过将空字符串或 null 作为第一个参数来“跳过”它,但这不起作用。必须使用命名参数方法。
以上是使用SASS默认参数的实用提示的详细内容。更多信息请关注PHP中文网其他相关文章!