Skip to content

@if 流程控制语句

@if() scss 内置函数允许您根据条件进行分支,并仅返回两种可能结果中的一种。

语法

语法 同 js 的 if....else if ...else

scss
.container {
  // 第一种
  @if (/* 条件 */) {
    // ...
  }

  // 第二种
  @if (/* 条件 */) {
    // ...
  } @else {
    // ...
  }

  // 第三种
  @if (/* 条件 */) {
    // ...
  } @else if() {
    // ...
  } @else {
    // ...
  }
}

定义一个 css 的三角形@mixin声明

scss
@mixin triangle($direction: top, $size: 30px, $border-color: blue) {
  width: 0px;
  height: 0px;
  display: inline-block;
  border-width: $size;
  border-#{$direction}-width: 0;
  @if ($direction == top) {
    border-color: transparent transparent $border-color transparent;
    border-style: dashed dashed solid dashed;
  } @else if($direction == right) {
    border-color: transparent transparent transparent $border-color;
    border-style: dashed dashed dashed solid;
  } @else if($direction == bottom) {
    border-color: $border-color transparent transparent transparent;
    border-style: solid dashed dashed dashed;
  } @else if($direction == left) {
    border-color: transparent $border-color transparent transparent;
    border-style: dashed solid dashed dashed;
  }
}

使用

scss
.p0 {
  @include triangle();
}
.p1 {
  @include triangle(right, 50px, red);
}
.p2 {
  @include triangle(bottom, 50px, white);
}
.p3 {
  @include triangle(left, 50px, green);
}

三元条件函数if()的使用

  • 语法
scss
if($condition,$if-true,$if-false);

判断$condition,如果条件成立,则返回$if-true 的结果,如果条件不成立,则返回$if-false 的结果。

  • 案例:if 的写法(浅色与深色模式)
scss
$theme: "light";
.container {
  @if $theme== "light" {
    color: #000;
  } @else {
    color: #fff;
  }
}

三元条件函数 if 改进

scss
$theme: "light";
.container {
  color: if($theme== "light", #000, #fff);
}