【问题标题】:Sass/scss multiple mixins combining stylesSass/scss 多个 mixins 组合样式
【发布时间】:2017-03-21 22:46:48
【问题描述】:

我有一个(嗯,真的有几个)Sass mixin 来设置渐变背景(具有向后兼容性等等)。现在,我有一个想要应用多个渐变的元素。我可以通过使用逗号分隔列表设置背景属性直接执行此操作,但如果我可以使用渐变混合的多个应用程序来应用多个渐变并将属性输出为通用分隔列表,我会喜欢它。

我想做的一个例子:

div.needs-two-backgrounds {
  @include gradient-mixin(90deg, $color-one 0, $color-two 100%);
  @include gradient-mixin(180deg, $color-three 0, $color-four 20%, $color-five 100%);
}

哪个(基本上)会发出这个

div.needs-two-backgrounds {
  background-image: linear-gradient(90deg, $color-one 0, $color-two 100%),
                    linear-gradient(180deg, $color-three 0, $color-four 20%, $color-five 100%);
}

有没有办法在 Sass 中内置,或者它需要一个单独的库,或者这对语言来说是不可能的?

编辑: 我根据答案构建了一个解决方案,并认为我会分享它。

@function linear-gradient-x($direction, $stops...) {
  @return linear-gradient($direction, $stops);
}

@function prefixed-background-image-list-x($prefix, $images) {
  $ret-val: ();

  @each $image in $images {
    $prefixed-image: #{$prefix}$image;
    $ret-val: append($ret-val, $prefixed-image, 'comma');
  }

  @return $ret-val;
}

@mixin background-image-x($backgrounds...) {
  background-image: prefixed-background-image-list-x("-moz-", $backgrounds);
  background-image: prefixed-background-image-list-x("-webkit-", $backgrounds);
  background-image: prefixed-background-image-list-x("-o-", $backgrounds);
  background-image: prefixed-background-image-list-x("ms-", $backgrounds);
  background-image: prefixed-background-image-list-x("", $backgrounds);
}

就像答案中建议的那样使用:

div.needs-two-backgrounds {
  @include background-image-x(
    linear-gradient-x(90deg, $color-one 0, $color-two 100%),
    linear-gradient-x(180deg, $color-three 0, $color-four 20%, $color-five 100%)
  );
}

希望这对某人有所帮助。

【问题讨论】:

    标签: sass mixins


    【解决方案1】:

    按照你描述的方式是不可能的,但是用这样的方式是可能的。

    div.needs-two-backgrounds {
        @include background-image(
            gradient(90deg, $color-one 0, $color-two 100%),
            gradient(180deg, $color-three 0, $color-four 20%, $color-five 100%)
        );
    }
    

    然后您必须创建一个支持可变参数的 mixin background-image - 注意三个点:

    @mixin background-image($images...) {
        // do stuff here
    }
    

    gradient-mixin 应替换为/扩展为 gradient 函数。 Compass 项目的 background-image mixin 是一个很好的起点:

    https://github.com/Compass/compass/blob/stable/core/stylesheets/compass/css3/_images.scss#L97

    【讨论】:

    • 抱歉,我花了一点时间才重新开始测试。
    猜你喜欢
    • 2018-03-15
    • 2018-03-26
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    相关资源
    最近更新 更多