我正在为Compass / Sass编写我的第一个mixin。经过一场短暂的战斗,我已经得到它来生成我需要的确切CSS;因此,我的问题不是关于修正输出,而是更多关于清理我完成它的方式。
以下是我正在使用的代码的两个片段。完整代码生成background-image:
CSS规则,其中包含任意数量的逗号分隔线性渐变,-webkit
,moz
和最新W3C格式的无前缀渐变声明(使用{{1}而不是to top
,例如)。
正如我所说,我对API和输出感到满意。我只是想清理这段代码。
首先,在下面的bottom
条件块中,我该如何避免我想要的内容:
w3c
...调用内置的Compass @return linear-gradient($direction, $color-stops);
mixin? (我在我的项目中包含了所有CSS3 Compass助手)。我想要的只是输出一个字符串,在括号内插入linear-gradient
和$direction
的值:
$color-stops
其次,是否有更简洁的方式编写下面的代码?我想循环所有@function -gradient-rule($type, $direction, $color-stops) {
@if $type == ('moz') {
@return -moz-linear-gradient($direction, $color-stops);
}
@if $type == ('webkit') {
@return -webkit-linear-gradient($direction, $color-stops);
}
@if $type == ('w3c') {
// Terrible, terrible hack. Just couldn't work out how to write this without invoking the built-in Compass linear-gradient() function
$prefix: linear-gradient;
@return #{$prefix}unquote("(")#{$direction}, #{$color-stops}unquote(")");
}
}
,并且对于每个$gradients
,假设第一项是方向声明,其余是颜色停止。因此,第一项应在变量$gradient
中设置,其余项设置在名为$to-direction
的逗号列表中。我怎样才能更好地做到这一点,即不需要$color-stops
计数器?
$i
非常感谢您提供任何帮助!
答案 0 :(得分:1)
1)除了用引号插入它之外你不能做很多事情。这是一个更干净的黑客:
@return #{"linear-gradient("+ $direction +", "+ $color-stops +")"}
PS你如何使用这段代码?
有点奇怪2)确实有一种更清洁的方式!
@for $gradient-number from 2 through length($gradients) {
$gradient: nth($gradients, $gradient-number);
$to-direction: nth($gradient, 1);
$color-stops: comma-list();
@each $prop in $gradient {
$color-stops: append($color-stops, $prop); }
...
$gradient-number
基本上与$i
相同,因此逻辑上差别不大,但代码整洁程度有很大差异。
当我第一次开始使用这个技巧时,我有点不舒服,但后来我也看到了SASS大师使用它(例如:1,2),所以我可以毫不费力地推荐给你思想。