我的较少代码是这样的:
body {
@var: white;
&.blue { @var: blue; }
&.red { @var: red; }
&.abc { @var: #badass; }
background-color: @var;
}
我希望的是,如果body
有类.abc
,变量的值@var
是#badass
,如果你有类.blue
,值是blue
等等。但这不是发生的事情,变量的值不会独立于它们的剩余类而改变。
You need to create a parametric mixin for that:
.bg(@color){
background-color:@color;
}
and then the following code will work:
body {
.bg("white");
&.blue{ .bg("blue"); }
&.red { .bg("red"); }
&.abc { .bg(#bada55); }
}
What you are doing isn't working, because you are reassigning the variable - which works perfectly, but not writing the new value to the class. (It would make absolutely no sense if LESS created new rules, every time you are just reassigning a variable.) Also, like any other programming language, LESS has scope, thus at the time it reaches background-color: @var;
@var
has the value white
assigned to it and creates the rule accordingly. This following will work (but makes no sense of course):
body {
@var: white;
&.blue{ @var: blue; background-color: @var;}
&.red { @var: red; background-color: @var;}
&.abc { @var: #bada55; background-color: @var;}
background-color: @var;
}