true 和 false
布尔值是逻辑值 true 和 false。除了它们的字面形式,布尔值还由相等和关系运算符以及许多内置函数(如 math.comparable() 和 map.has-key())返回。
布尔值是逻辑值 true 和 false。除了它们的字面形式,布尔值还由相等和关系运算符以及许多内置函数(如 math.comparable() 和 map.has-key())返回。
@use "sass:math";
@debug 1px == 2px; // false
@debug 1px == 1px; // true
@debug 10px < 3px; // false
@debug math.comparable(100px, 3in); // true
@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 运算符返回单个布尔值的相反值。
@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
@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 时评估一个样式块:
@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);
}
@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)
.square-av {
width: 100px;
height: 100px;
}
.circle-av {
width: 100px;
height: 100px;
border-radius: 50px;
}
if() 函数如果其参数为 true 则返回一个值,如果其参数为 false 则返回另一个值:
@debug if(true, 10px, 30px); // 10px
@debug if(false, 10px, 30px); // 30px
@debug if(true, 10px, 30px) // 10px
@debug if(false, 10px, 30px) // 30px
真值和假值
在任何允许 true 或 false 的地方,你也可以使用其他值。false 和 null 值是假值,这意味着 Sass 认为它们表示虚假并导致条件失败。所有其他值都被认为是真值,因此 Sass 认为它们的作用类似于 true 并导致条件成功。
例如,如果你想检查一个字符串是否包含空格,你只需编写 string.index($string, " ")。string.index() 函数如果找不到字符串则返回 null,否则返回一个数字。
有些语言认为比
false 和 null 更多的值是假值。Sass 不是其中之一!空字符串、空列表和数字 0 在 Sass 中都是真值。