有条件地根据另一个变量设置一个变量的值 [英] Conditionally setting one variable's value based on another

查看:56
本文介绍了有条件地根据另一个变量设置一个变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为@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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆