2012-12-30 29 views
4

基本上我想從mixin訪問變量@b以供別處使用。什麼我試圖做一個例子如下,但是,這並不工作:從一個單獨的mixin訪問一個較小的變量

.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; 
} 

任何幫助將不勝感激,謝謝你提前。

傑森

+0

還有什麼更多的'.mixin'或它只是用來計算'@ b'? – ScottS

+0

是的,還有更多,但我已經簡化了導致這個問題的代碼。 – user1937392

回答

2

顯然,你的主要問題是在這裏變量範圍。在another answer of mine的基礎上,有些情況下你可以在mixin中設置一個變量,並在mixin之外使用它,但正如答案所示,LESS中的一個明顯錯誤阻止了通過傳入其他變量來設置該變量(這就是你需要在這裏)。注意:據說這個bug是固定的,所以也許LESS編譯器的最新下載可能會解決你的問題;我知道我通常在測試的在線編譯器仍然不允許這種類型的變量設置。

所以這裏是另一個建議的替代方案:在.mixin內創建你需要的嵌套參數混合,這使得@b完全可以訪問。

所以這LESS

@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; 
+0

感謝,似乎已經解決了它,但哇,這是一個瘋狂的數量的代碼,以使其工作。再次感謝。 – user1937392

+0

@ user1937392:真的,它只是略多一點的代碼;只是將代碼從'item' mixin移動到'mixin' mixin。我在示例中添加了一個額外的'item'來顯示它的工作。 – ScottS

+0

我的歉意已經認識到,你編碼的方式實際上更有效,並且可以進一步防止重複。再次感謝。 – user1937392