有条件地根据另一个变量设置一个变量的值 [英] Conditionally setting one variable's value based on another
问题描述
我有一个名为@side
的Less变量.我要根据@side
变量的值设置变量@sideOpposite
.它只能使用两个值:"left"或"right".
I've got a Less variable called @side
. What I want is to set the variable @sideOpposite
depending on the value of the @side
variable. It can take only two values: "left" or "right".
换句话说,我需要一个不太等价的JS代码:
In other words I need a Less equivalent of the JS code:
var side = "left",
sideOpposite = (side === "left")? "right" : "left";
我尝试使用when
函数来完成此操作,但是据我了解,它不能那样工作,并且仅适用于CSS属性,不适用于变量:
I've tried to accomplish this using when
function, but from what I understand it doesn't work that way and is only applicable to CSS properties, not variables:
when (@side = right){
@sideOpposite: left;
}
when (@side = left){
@sideOpposite: right;
}
推荐答案
请参见 Mixin Guards 和规则集守卫(又称"CSS Guards")有关when
用法示例.由于需要定义变量,因此必须使用基于混合的条件(规则集不会将其变量暴露给外部作用域).例如:
See Mixin Guards and Ruleset Guards (aka "CSS Guards") for when
usage examples. Since you need to define a variable you'll have to use mixin-based condition (rulesets do not expose their variables to an outer scope). E.g.:
.-();
.-() when (@side = right) {
@sideOpposite: left;
}
.-() when (@side = left) {
@sideOpposite: right;
}
(使用任何合适的混合名称代替.-
,例如.define-opposite-side
).
(Use any suitable mixin name instead of .-
, e.g. .define-opposite-side
).
通过参数模式匹配,可以进一步简化此操作只是为了:
And with Argument Pattern Matching it can be further simplified just to:
.-(@side);
.-(left) {@sideOpposite: right}
.-(right) {@sideOpposite: left}
这篇关于有条件地根据另一个变量设置一个变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!