2017-10-12 72 views
1

我有,目前有两种颜色的渐变一个mixin:如何在mixin中处理可变数量的参数?

@mixin gradient($color-start, $color-end) { 
    background-image: linear-gradient(90deg, $color-start 0%, $color-end 100%); 
} 

,我到处使用像这样

.my-gradient { 
    @include gradient(blue, yellow) 
} 

,但现在我想修改混入(或将其转换为一个函数),可以采用两个三个参数作为渐变。

像(伪代码):

@mixin gradient($color-start, $color-end, $color-center) { 
    ...if $color-center param exists... 
    background-image: linear-gradient(90deg, $color-start 0%, $color-center 50%, $color-end 100%); 
    ...if $color-center param does not exist... 
    background-image: linear-gradient(90deg, $color-start 0%, $color-end 100%); 
} 

我不知道的处理这种情况的最好办法。

+1

这是否回答帮助? https://stackoverflow.com/a/9960403/5561605 – sol

回答

1

你可以在你的mixin中编写if-else子句!

@mixin gradient($color-start, $color-end, $color-center:null) { 
    @if($color-center){ 
     background-image: linear-gradient(90deg, $color-start 0%, $color-center 50%, $color-end 100%); 
    }@else{ 
     background-image: linear-gradient(90deg, $color-start 0%, $color-end 100%);  
    } 

} 

.test_1{ 
    @include gradient(#000, #111); 
} 

.test_2{ 
    @include gradient(#111,#222,#333); 
} 

输出:

.test_1 { 
    background-image: linear-gradient(90deg, #000 0%, #111 100%); 
} 

.test_2 { 
    background-image: linear-gradient(90deg, #111 0%, #333 50%, #222 100%); 
} 

注意,我的$color-center的参数值设置为null否则会有一个错误,如果你只通过2个参数