2015-01-08 53 views
0

我想創建一個帶兩個變量中的一個的Mixin,並根據傳遞的變量創建填充按鈕或輪廓按鈕。創建帶和不帶邊框的Mixin

@include button-style($color: red); 

// would result in 
background-color: transparent; 
color: red; 
box-shadow: inset 0 0 0 1px red; 

@include button-style($bg: red); 

// would result in 
background-color: red; 
color: white; 

有沒有辦法做到這一點?我在這裏試圖找出最簡單的方法來實現這一目標。這是迄今爲止我所擁有的。

@mixin button-style($bg: transparent, $color: white) { 
    background-color: $bg; 
    color: $color; 
    @if $color == 'white' { 
    box-shadow: inset 0 0 0 1px $color; 
    } 
} 

任何幫助表示讚賞。提前致謝!

回答

1

這似乎爲我工作。我建立了一個working example over here。唯一的缺點是我有綁transparent給一個變量,像這樣:

$transparent: transparent; 

@mixin button-style($bg: $transparent, $color: white) { 
    background-color: $bg; 
    color: $color; 
    @if $bg == $transparent { 
    box-shadow: inset 0 0 0 1px $color; 
    } 
} 

.button-pri { 
    @include button-style($bg: red); 
} 

.button-sec { 
    @include button-style($color: red); 
} 

如果可能的話,我想削減該變量的方程,直走if $bg == 'transparent { ...,但if聲明不似乎與一個字符串一起工作。

更新

感謝@KreaTief,顯然我並不需要使用一個變量。更新回答如下:

@mixin button-style($bg: transparent, $color: white) { 
    background-color: $bg; 
    color: $color; 
    @if $bg == transparent { 
    box-shadow: inset 0 0 0 1px $color; 
    } 
} 

.button-pri { 
    @include button-style($bg: red); 
} 

.button-sec { 
    @include button-style($color: red); 
} 
+1

實際上,如果你的作品寫if語句爲@if $ bg ==透明 - > http://sassmeister.com/gist/849233dd8093680c3f46 – KreaTief

+0

謝謝duder!上面更新了答案。 – realph

+0

不客氣:) – KreaTief

1

添加一個額外的參數並針對該參數執行檢查。

@mixin button-style($bg: transparent, $color: white, $border: true) { 
    background-color: $bg; 
    color: $color; 
    @if $border { 
    box-shadow: inset 0 0 0 1px $color; 
    } 
} 

.foo { 
    @include button-style; 
} 

.bar { 
    @include button-style($border: false); 
} 

輸出:

.foo { 
    background-color: transparent; 
    color: white; 
    box-shadow: inset 0 0 0 1px white; 
} 

.bar { 
    background-color: transparent; 
    color: white; 
} 

或者,您也可以使用空值:

@mixin button-style($bg: transparent, $color: white, $border: inset 0 0 0 1px $color) { 
    background-color: $bg; 
    color: $color; 
    box-shadow: $border; 
} 

.foo { 
    @include button-style; 
} 

.bar { 
    @include button-style($border: null); 
} 
+0

我寧願在'@ include'中沒有額外的參數,如果這是可能的?也許這是不可能的... – realph

+0

它要麼添加額外的參數,要麼將其綁定到其他參數之一,以便背景或顏色必須設置爲了獲得邊框。有第三種選擇,但它明顯更加冗長。 – cimmanon

+0

如果/ else語句接受字符串,Mixin可以混合嗎?例如,'@if $ color =='white'' ?? – realph