2012-07-10 114 views
4

我知道LESS沒有if/else結構,而是依賴於保護的mixin語句。儘管如此,它似乎無法在mixin中設置LESS CSS變量。你可以在LESS CSS的mixin中設置一個變量嗎?

任何人都有我如何實現某些東西的效果的想法。

if(ispercentage(@height) { 
    @height: "1024px"; 
} 

// Calculations dependent on @height 
@textAreaHeight = 0.5 * @height; 
@buttonHeight = 0.2 * @height; 

我看了其他幾個計算器的問題包括: LESS CSS - Setting variable within mixin

+0

您應該使用:而不是等號(=),但你已經知道了。 – 2012-07-10 22:16:06

回答

2

是的,它可以做到。有一個錯誤需要解決。

例更少的代碼

//Set up guarded mixins 
.setHeight(@h) when (ispercentage(@h)) { 
    @height: 1024px; 
} 

.setHeight(@h) when not (ispercentage(@h)) { 
    @height: @h; 
} 

//set up main height 
@mainHeight: 50%; 
body { height: @mainHeight;} 

//call it by itself to make global 
//.setHeight(@mainHeight); <-this failed (appears to be a bug) 
.setHeight(50%); // <-this worked 

.subsection { height: @height; /* just to show it is setting it */} 

//use it for other globals 
@textAreaHeight: 0.5 * @height; 
@buttonHeight: 0.2 * @height; 

textarea { height: @textAreaHeight} 
button { height: @buttonHeight} 

//override it locally 
body.fixedHeight { 
    .setHeight(300px); 
    @textAreaHeight: 0.333 * @height; 
    height: @height; 
    textarea { height: @textAreaHeight} 
} 

範例CSS輸出

body { 
    height: 50%; 
} 
.subsection { 
    height: 1024px; /* just to show it is setting it */ 
} 
textarea { 
    height: 512px; 
} 
button { 
    height: 204.8px; 
} 
body.fixedHeight { 
    height: 300px; 
} 
body.fixedHeight textarea { 
    height: 99.9px; 
} 
+0

@ blak3r - 我[提交問題](https://github.com/cloudhead/less.js/issues/878)與變量的傳遞。 – ScottS 2012-07-26 18:32:33

1

您可以創建一個由類型爲「守衛」一個mixin,例如

.doHeightSet(@height) when ispercentage(@height) { 
    .doheightSet(1024px) 
} 

.doHeightSet(@height) when not ispercentage(@height) { 
    // Calculations dependent on @height 
    @textAreaHeight: 0.5 * @height; 
    @buttonHeight: 0.2 * @height; 

    /* use variables here */ 
} 

對不起,我沒有時間來試試,所以我可能犯了一個語法錯誤。

編輯已更正的語法。

+0

我不認爲你可以在mixin中設置一個變量。你可以嗎?我試着玩弄它,並沒有得到任何東西來編譯。 – blak3r 2012-07-12 00:58:20

+0

哎呦應該是:不是= – 2012-07-13 07:04:02

相關問題