1

我的较少代码是这样的:

body {
  @var: white;

  &.blue { @var: blue; }
  &.red { @var: red; }
  &.abc { @var: #badass; }

  background-color: @var;
}

我希望的是,如果body有类.abc,变量的值@var#badass,如果你有类.blue,值是blue等等。但这不是发生的事情,变量的值不会独立于它们的剩余类而改变。

4

1 回答 1

2

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;
}
于 2012-08-07T12:46:36.263 回答