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