【问题标题】:Compass/Sass function & mixin syntaxCompass/Sass 函数和 mixin 语法
【发布时间】:2012-10-03 03:16:20
【问题描述】:

我目前正在为 Compass/Sass 编写我的第一个 mixin。经过短暂的战斗,我已经得到它来生成我需要的确切 CSS;因此我的问题不是关于修复输出,而是更多关于清理我完成它的方式。

这是我正在使用的代码的两个 sn-ps。完整的代码会生成一个background-image: CSS 规则,其中包含任意数量的逗号分隔的线性渐变,-webkitmoz 和最新 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


【解决方案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),所以我可以毫不犹豫地推荐给你。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-11
    • 2012-04-26
    • 1970-01-01
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    • 2012-09-23
    相关资源
    最近更新 更多