布林值
布林值是邏輯值 true
和 false
。除了它們的字面形式之外,布林值也會由等於和關係運算子返回,以及許多內建函式,例如 math.comparable()
和 map.has-key()
。
SCSS 語法
@use "sass:math";
@debug 1px == 2px; // false
@debug 1px == 1px; // true
@debug 10px < 3px; // false
@debug math.comparable(100px, 3in); // true
Sass 語法
@use "sass:math"
@debug 1px == 2px // false
@debug 1px == 1px // true
@debug 10px < 3px // false
@debug math.comparable(100px, 3in) // true
您可以使用布林運算子來處理布林值。and
運算子在*兩邊*都為 true
時返回 true
,而 or
運算子在*任一邊*為 true
時返回 true
。not
運算子返回單一布林值的相反值。
SCSS 語法
@debug true and true; // true
@debug true and false; // false
@debug true or false; // true
@debug false or false; // false
@debug not true; // false
@debug not false; // true
Sass 語法
@debug true and true // true
@debug true and false // false
@debug true or false // true
@debug false or false // false
@debug not true // false
@debug not false // true
使用布林值使用布林值 永久連結
您可以使用布林值來選擇是否在 Sass 中執行各種操作。@if
規則在其參數為 true
時評估程式碼區塊
SCSS 語法
@use "sass:math";
@mixin avatar($size, $circle: false) {
width: $size;
height: $size;
@if $circle {
border-radius: math.div($size, 2);
}
}
.square-av {
@include avatar(100px, $circle: false);
}
.circle-av {
@include avatar(100px, $circle: true);
}
Sass 語法
@use "sass:math"
@mixin avatar($size, $circle: false)
width: $size
height: $size
@if $circle
border-radius: math.div($size, 2)
.square-av
@include avatar(100px, $circle: false)
.circle-av
@include avatar(100px, $circle: true)
CSS 輸出
.square-av {
width: 100px;
height: 100px;
}
.circle-av {
width: 100px;
height: 100px;
border-radius: 50px;
}
if()
函式在其參數為 true
時返回一個值,在其參數為 false
時返回另一個值。
真值與假值真值與假值 永久連結
在允許 true
或 false
的任何地方,您也可以使用其他值。值 false
和 null
是*假值*,這表示 Sass 將它們視為表示錯誤並導致條件失敗。其他所有值都被視為*真值*,因此 Sass 將它們視為像 true
一樣工作並導致條件成功。
舉例來說,如果您想檢查字串是否包含空格,您可以直接寫 string.index($string, " ")
。string.index()
函式如果找不到字串會回傳 null
,否則會回傳一個數字。
⚠️ 注意!
有些語言除了 false
和 null
之外,還有其他值被視為假值。Sass 並非如此!在 Sass 中,空字串、空串列和數字 0
都被視為真值。