• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • @if 和 @else

    @if规则是编写的@if<expression>{...},它控制其块是否被评估(包括发出任何样式作为 CSS)。表达式通常返回true或者false。如果表达式返回true,则计算块,如果表达式返回false,则不计算。

    scss 语句css 语句
    @mixin avatar($size, $circle: false) {
      width: $size;
      height: $size;
    
      @if $circle {
        border-radius: $size / 2;
      }
    }
    
    .square-av {
      @include avatar(100px, $circle: false);
    }
    .circle-av {
      @include avatar(100px, $circle: true);
    }
    
    .square-av {
      width: 100px;
      height: 100px;
    }
    
    .circle-av {
      width: 100px;
      height: 100px;
      border-radius: 50px;
    }
    


    @else

    一个@if规则可以选择跟随一个@else规则,写成@else{...}。如果@if表达式返回false,则计算该规则的块。

    scss 语句css 语句
    $light-background: #f2ece4;
    $light-text: #036;
    $dark-background: #6b717f;
    $dark-text: #d2e1dd;
    
    @mixin theme-colors($light-theme: true) {
      @if $light-theme {
        background-color: $light-background;
        color: $light-text;
      } @else {
        background-color: $dark-background;
        color: $dark-text;
      }
    }
    
    .banner {
      @include theme-colors($light-theme: true);
      body.dark & {
        @include theme-colors($light-theme: false);
      }
    }
    
    .banner {
      background-color: #f2ece4;
      color: #036;
    }
    body.dark .banner {
      background-color: #6b717f;
      color: #d2e1dd;
    }
    


    @else if

    您还可以通过编写@else if&;t;expression>{...},来选择是否计算规则的块。如果这样做,则仅当前面的@if的表达式返回false,而@else if的表达式返回true时,才会计算块。

    实际上,您可以在@else if之后链接任意数量的@else if。将计算链中表达式返回true的第一个块,而不计算其他块。如果在链的末端有一个普通的@else,那么如果每个其他块都失败,则将对其块进行评估。

    scss 语句css 语句
    @use "sass:math";
    
    @mixin triangle($size, $color, $direction) {
      height: 0;
      width: 0;
    
      border-color: transparent;
      border-style: solid;
      border-width: math.div($size, 2);
    
      @if $direction == up {
        border-bottom-color: $color;
      } @else if $direction == right {
        border-left-color: $color;
      } @else if $direction == down {
        border-top-color: $color;
      } @else if $direction == left {
        border-right-color: $color;
      } @else {
        @error "Unknown direction #{$direction}.";
      }
    }
    
    .next {
      @include triangle(5px, black, right);
    }
    
    .next {
      height: 0;
      width: 0;
      border-color: transparent;
      border-style: solid;
      border-width: 2.5px;
      border-left-color: black;
    }
    


    真与假

    在允许任何地方truefalse的地方,您也可以使用其他值。falsenull的值是 falsey,这意味着 Sass 认为它​​们表示错误并导致条件失败。其他所有值都被认为是真实的,因此 Sass 认为它​​们的工作方式类似true并导致条件成功。

    例如,如果要检查字符串是否包含空格,则只需编写string.index($string," ").如果未找到该字符串,则该string.index()函数,返回null,否则返回一个数字。

    ⚠️注意!
    一些语言认为更多的值是虚假的,而不仅仅是falsenull。Sass 不是其中一种语言!空字符串空列表和数字0,在 Sass 中,都是真值。

    下篇:@each