【发布时间】:2012-10-03 03:16:20
【问题描述】:
我目前正在为 Compass/Sass 编写我的第一个 mixin。经过短暂的战斗,我已经得到它来生成我需要的确切 CSS;因此我的问题不是关于修复输出,而是更多关于清理我完成它的方式。
这是我正在使用的代码的两个 sn-ps。完整的代码会生成一个background-image: CSS 规则,其中包含任意数量的逗号分隔的线性渐变,-webkit、moz 和最新 W3C 格式的无前缀渐变声明(使用 to top 而不是 bottom,例如例子)。
正如我所说,我对 API 和输出感到满意。我只想清理这段代码。
首先,在下面的w3c 条件块中,我怎样才能避免我想要的:
@return linear-gradient($direction, $color-stops);
... 调用内置 Compass linear-gradient mixin? (我在我的项目中包括了所有的 CSS3 Compass 助手)。我只想输出一个字符串,在括号内插入$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 计数器?
@each $gradient in $gradients {
$i: 1;
$to-direction: nth($gradient, 1);
$color-stops: comma-list();
@each $prop in $gradient {
@if $i > 1 {
$color-stops: append($color-stops, $prop);
}
$i: $i+1;
}
// old syntax is the origin of the gradient, not the destination
$from-direction: -from-direction($to-direction);
$moz-value: append($moz-value, -gradient-rule('moz', $from-direction, $color-stops));
$webkit-value: append($webkit-value, -gradient-rule('webkit', $from-direction, $color-stops));
// new syntax is the destination
$w3c-value: append($w3c-value, -gradient-rule('w3c', $to-direction, $color-stops));
...
(continues)
}
非常感谢您提供的任何帮助!
【问题讨论】:
-
我对 Compass 梯度 mixin 不熟悉,你的 mixin 有什么不同?
-
你能把你所有的代码都扔到codepen吗?能够玩耍会让事情变得更容易:)
标签: css sass compass-sass