变量 – 从单独的mixin访问less变量

基本上我想从mixin访问变量@b以供其他地方使用.我想要做的一个例子如下,但这不起作用:

.mixin (@x:@x, @y:@y, @z:@z) {
       @b: (@x + @y) / @z; 
}

.item (@x:@x, @y:@y, @z:@z) {
       .mixin (@x, @y, @z);
       margin-left: @b;
 }

.item2 (@x:@x, @y:@y, @z:@z) {
       .mixin (@x, @y, @z);
       margin-right: @b;
}

任何帮助将不胜感激,并提前感谢您.

贾森

最佳答案 显然,这里的主要问题是变量范围.基于
another answer of mine,有些情况下你可以在mixin中设置一个变量并让它在mixin之外可用,但正如答案所示,LESS中的一个明显的错误阻止了通过传入其他变量来设置变量(这是什么你需要这里).注意:据说错误已修复,因此最新的LESS编译器下载可能会解决您的问题;我知道我通常测试的在线编译器仍然不允许这种类型的变量设置.

所以这里有另一个建议的选择:在你的.mixin中创建你需要的嵌套参数mixin,这使得@b完全可以访问.

所以这很少

@x: 3;
@y: 3;
@z: 2;

.mixin (@x:@x, @y:@y, @z:@z, @bProp: null) {
       //all your other mixin code

       @b: (@x + @y) / @z;

       //set up pattern matching for props
       //that need @b

       .prop(null) {} //default none
       .prop(ml) {
          margin-left: @b;
       }
       .prop(mr) {
          margin-right: @b;
       }
       //call the property
       .prop(@bProp);
}

.item (@x:@x, @y:@y, @z:@z) {
       //this is a pure default of .mixin()
       .mixin (@x, @y, @z); 
 }

.item1 (@x:@x, @y:@y, @z:@z) {
       //this is set up to call the margin-left pattern
       .mixin (@x, @y, @z, ml);
 }

.item2 (@x:@x, @y:@y, @z:@z) {
       //this is set up to call the margin-right pattern
       .mixin (@x, @y, @z, mr);
}

.item(); 
.item1(); 
.item2(6,6,3);

生成这个CSS(显然它实际上会在选择器中使用,但我认为你明白了).

//note that nothing is produced for .item() because it
//defaults to no extra properties other than the base .mixin()
margin-left: 3;
margin-right: 4;
点赞