@if、@else、@else-if 允许我们像 JavaScript 一样控制 SASS 文件编译中的流程。
- @if :如果条件表达式的值为真,@if 块将被编译。
句法:
@if
{ ... } 示例 1: SASS 文件
@mixin button-format( $round-button, $size ) { color: white; background-color: blue; width: $size; @if $round-button { height: $size; border-radius: $size / 2; } } .mybutton{ @include button-format(false, 100px); }
示例 1:编译的 CSS 文件
.mybutton { color: white; background-color: blue; width: 100px; }
示例 2: SASS 文件
@mixin button-format( $round-button, $size ) { color: white; background-color: blue; width: $size; @if $round-button { height: $size; border-radius: $size / 2; } } .mybutton{ @include button-format(true, 100px); }
示例 2:编译的 CSS 文件
.mybutton { color: white; background-color: blue; width: 100px; height: 100px; border-radius: 50px; }
- @else:如果上述所有@if 或@else-if 块的条件表达式的值为false,则编译该块。
句法:
@else { ... }
SASS文件:
@mixin theme ($theme-decide, $r, $g, $b) { // light background @if $theme-decide { background-color: rgba($r, $g, $b, 0.5); } // dark background @else { background-color: rgba($r, $g, $b, 1); // red color } } .myblock { @include theme(false, 255, 0, 0); }
编译后的 CSS 文件:
.myblock { background-color: red; // if true value is passed then rgba(255, 0, 0, 0.5); }
- @else if:将编译第一个带有条件表达式值为 true 的 @else-if 块。如果没有@else-if 块表达式计算为真,那么@else 块将被编译。
句法:
@else if
{ ... } SASS文件:
@mixin theme ($theme-decide, $r, $g, $b) { // light background @if $theme-decide == 1 { background-color: rgba($r, $g, $b, 0.5); } // medium-dark background @else if $theme-decide == 2 { background-color: rgba($r, $g, $b, 0.7); } // dark background @else { background-color: rgba($r, $g, $b, 1); } } .myblock { @include theme(2, 0, 255, 0); }
编译后的 CSS 文件:
.myblock { background-color: rgba(0, 255, 0, 0.7); }