
Sass @if 语句条件判断错误及解决方案
在使用 Sass 的 @if 语句进行条件判断时,不正确的语法可能会导致判断结果错误。 以下示例展示了一个常见的错误:
@if([typeset="card"] && [exercise-type="choice"])
> span
font-size: 12px !important
@else
> span
font-size: 14px !important
预期:当 typeset 为 "card" 且 exercise-type 为 "choice" 时,字体大小为 12px;否则为 14px。
实际:无论条件如何,字体大小始终为 12px。
错误原因及解决方案
问题在于 Sass 中 && 运算符的优先级以及对 [attribute="value"] 语法的误解。 [attribute="value"] 并非 Sass 的标准属性选择器,它在 Sass 中并不直接代表属性值的判断。 正确的做法是使用 Sass 的变量或内建函数来访问和比较属性值。
假设 typeset 和 exercise-type 是预先定义的 Sass 变量,或者可以通过其他方式获取,那么正确的 @if 语句应该如下:
$typeset: card;
$exercise-type: choice;
@if ($typeset == "card" and $exercise-type == "choice")
> span
font-size: 12px !important
@else
> span
font-size: 14px !important
或者,如果这些值来自 CSS 类名,可以使用 if 函数结合字符串操作:
@function check-condition($selector) {
@if (str-index($selector, 'typeset-card') and str-index($selector, 'exercise-type-choice')) {
@return true;
} @else {
@return false;
}
}
.my-element {
@if (check-condition(selector)) {
> span {
font-size: 12px !important;
}
} @else {
> span {
font-size: 14px !important;
}
}
}
这个例子假设你的类名类似于 typeset-card 和 exercise-type-choice。 str-index 函数检查字符串是否包含子字符串。 你需要根据你的实际 CSS 类名结构调整 check-condition 函数。
通过使用正确的 Sass 语法和变量,可以避免条件判断错误,并确保 @if 语句能够按照预期工作。 记住,[attribute="value"] 在 Sass 中不是有效的属性值判断方式。 使用 == 进行比较,并确保你的变量已正确定义。









