如何在LESS css中增加变量? 这是一个例子.. @counter: 1;.someSelector("nameOfClass",@counter);@counter: @counte
...如何在LESS css中增加变量?
这是一个例子..
@counter: 1;.someSelector("nameOfClass",@counter);@counter: @counter + 1;.someSelector("nameOfClass",@counter);
上面的代码片段会导致此“语法错误”
SyntaxError: Recursive variable definition for @counter
是否有解决此错误的方法?比如有一个像@counter这样的符号吗?
谢谢..
.解决方法
. 不是非常可能的参见the documentation on LESS variables.基本上,LESS变量是其创建范围内的常量.它们是懒惰的,并且不能以这种方式“改变”.最后一个定义将是该范围内所有人使用的定义.在您的情况下,将发生错误,因为变量不能引用自己.
考虑这个例子:
@counter: 1;.someSelector("nameOfClass",@counter);@counter: 2;.someSelector("nameOfClass1",@counter);.someSelector(@name; @count) { @className: ~"@{name}"; .@{className} { test: @count; }}
两者的输出均为2:
.nameOfClass { test: 2;}.nameOfClass1 { test: 2;}
这是因为LESS使用该范围中变量的最后定义来定义@counter.它没有注意使用@counter的调用顺序,而是像CSS一样,并考虑变量的“级联”.
有关在LESS中进一步讨论的内容,您可以跟踪this LESS feature request上发生的讨论.
解决方案是在本地变量的递归调用设置器中
七段 – 最大linked到他认为是LESS中的一个错误,但我认为不是.相反,在我看来,创造性地使用递归重置计数器来获得所需的效果.这允许你实现你想要的(使用我的示例代码):
// counter.init() {.inc-impl(1); // set initial value} .init();.inc-impl(@new) {.redefine() {@counter: @new;}}.someSelector(@name) { .redefine(); // this sets the value of counter for this call only .inc-impl((@counter + 1)); // this sets the value of counter for the next call @className: ~"@{name}"; .@{className} { test: @counter; }}.someSelector("nameOfClass");.someSelector("nameOfClass1");
这是CSS输出:
.nameOfClass { test: 1;}.nameOfClass1 { test: 2;}
注意:我相信您并未严格更改全局值,而是在每次调用.someSelector时设置新的本地值.这是否基于有缺陷的行为是值得怀疑的,但如果是这样,这个解决方案将来可能会消失.
有关此方法的局限性的进一步评论,see the discussion here.