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中文網其他相關文章!