2015-01-08 52 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