SASS如何使用@if和@else?代码示例

2021年3月27日17:34:36 发表评论 607 次浏览

@if, @else, @else-if允许我们控制JavaScript之类的SASS文件编译中的流程。

@if:如果条件表达式的值为true, 则将编译@if块。

语法如下:

@if <conditional_expression> { ... }

范例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块表达式的结果为true, 则将编译@else块。

语法如下:

@else if <conditional_expression> { ... }

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);
}

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: