指南针/ Sass函数和mixin语法

3
我目前正在为Compass/Sass编写我的第一个mixin。经过一番努力,我已经使它生成了确切需要的CSS;因此我的问题不在于修复输出,而是如何清理我所做的事情。
这里有两段我正在使用的代码片段。完整代码生成一个包含任意数量逗号分隔线性渐变的background-image:CSS规则,并在最新的W3C格式中使用to top而不是bottom来生成webkit,moz和未加前缀的渐变声明。
正如我所说,我对API和输出感到满意。我只想清理一下这个代码。
首先,在下面的w3c条件块中,如何避免我想要的:
@return linear-gradient($direction, $color-stops);

...如何调用内置的Compass linear-gradient混合器?(我的项目中包含所有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有什么不同之处? - cimmanon
你能把你的所有代码放到codepen上吗?这样能够轻松地进行调试,会让事情变得更加容易 : ) - Nick Tomlin
1个回答

1

1) 除了在引号中插值之外,你无法做太多事情。以下是一个相对更清晰的hack:

@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大师也在使用它(例如:12),所以我毫不犹豫地向您推荐它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接