使用 SCSS,我想创建一个 mixin,它将接收参数并可以确定它是颜色还是渐变,并根据它创建 background
属性。
作为可能的参数输入:
- 任何颜色值(#hex、rgba、color...)。
- 任何颜色 SCSS 函数(
rgba(color, 0.1)
,darken(color, 15%)
...)作为颜色。 - 渐变字符串("top, rgba(30,87,153,1) 0%,rgba(125,185,232,1) 100%")
伪代码:
if color or SCSS color function
then background: color;
if gradient
then background: -webkit-linear-gradient(gradient);
background: linear-gradient(gradient);
background: -moz-linear-gradient(gradient);
我不想使用 Compass 或任何其他 SASS 库。
最佳答案
Note: I don't recommend using Sass or Less mixins for performing vendor prefixing. More so for gradients because the old gradient syntax and the new ones are not the same. It is better to leave these sort of things to small libraries like prefix-free or Auto-prefixer etc.
要回答您的问题,是的,可以区分颜色(或颜色函数输出)和字符串 using the type_of
function .
下面是一个片段,可以满足您的需要。我没有添加任何解释,因为我觉得它是不言自明的。如果您发现代码的任何部分很复杂,请给我留言,我会解释更多。
@mixin bg($value){
@if type_of($value) == 'color' {
background: $value;
}
@else if type_of($value) == 'string' {
background: -webkit-linear-gradient(#{$value});
background: -moz-linear-gradient(#{$value});
background: linear-gradient(#{$value});
}
@else {
@error "Invalid parameter. Mixin expects a color or color function or gradient as value. ";
}
}
#demo.color {
@include bg(red);
}
#demo.gradient {
@include bg('top, rgba(30,87,153,1) 0%,rgba(125,185,232,1) 100%');
}
#demo.color-rgba {
@include bg(rgba(127, 127, 127, 0.1));
}
#demo.color-rgba-sass {
@include bg(rgba(red, 0.1));
}
#demo.color-hex {
@include bg(#0f0);
}
#demo.color-function {
@include bg(darken(red, 15%));
}
/* #demo.invalid-value { if this is uncommented, you'd get the error
@include bg(1);
}*/
CodePen Demo (单击 CSS 选项卡上的“查看已编译”按钮以查看输出)
关于css - SCSS mixin 或函数来区分颜色或渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38039756/