【问题标题】:Strange character appending to SCSS @mixin附加到 SCSS @mixin 的奇怪字符
【发布时间】:2018-10-25 20:48:30
【问题描述】:

在以下场景中,我需要支持尽可能多的浏览器。

我正在构建一个 SCSS @mixin,它在 background-image 前面加上供应商前缀,但还会监听 linear-gradient 是否被声明,如果是,那么也加上前缀。

我的代码如下所示:

@function str-coerce($string) {
  @return inspect($string);
}

@function str-replace($string, $find, $replace: "") {
  $index: str-index($string, $find);

  @if $index {
    @return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($find)), $find, $replace);
  }

  @return $string;
}

@mixin background-image($values...) {
  $vendors: (-webkit-, -moz-, -o-);

  @each $vendor in $vendors {
    $string: str-coerce($values);

    @if (str-index($string, "linear-gradient")) {
    $string: str-replace($string, "linear-gradient", #{$vendor + "linear-gradient"});

    @if (str-index($vendor, "-o-")) {
      $vendor: str-replace($vendor, "-o-");
    }

    #{$vendor + "background-image"}: $string;
    } @else {

      @if not (str-index($vendor, "-o-")) {
        #{$vendor + "background-image"}: $values;
      }
    }
  }

  background-image: $values;
}

用法和输出如下所示:

// usage
.foo {
  @include background-image(url("../example.svg"));
}
.bar {
  @include background-image(linear-gradient(45deg, red, blue));
}

// output
.foo {
  -webkit-background-image: url("../example.svg");
  -moz-background-image: url("../example.svg");
  background-image: url("../example.svg");
}
.bar {
  -webkit-background-image: (-webkit-linear-gradient(45deg, red, blue),);
  -moz-background-image: (-moz-linear-gradient(45deg, red, blue),);
  background-image: (-o-linear-gradient(45deg, red, blue),);
  background-image: linear-gradient(45deg, red, blue);
}

我的问题是,我的类型强制中出了什么问题,导致我的 linear-gradient 供应商前缀被括在括号中并后跟逗号?例如(-moz-linear-gradient(45deg, red, blue),).

【问题讨论】:

  • 可以给我str-replace的代码吗?
  • 抱歉——我的疏忽——我现在添加了str-replace函数。

标签: css sass scss-mixins


【解决方案1】:

虽然我不完全确定您的值为何被包装在 () 中,但您可以使用 str-replace 函数来删除它们。

要删除领先的(,请将您的str-replace 函数更新为:

@function str-replace($string, $search, $replace: '') {
  $index: str-index($string, $search);

  @if $index {
    @return str-slice($string, 1, $index - 2) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
  }

  @return $string;
}

然后更新此行以删除尾随的),

  #{$vendor + "background-image"}:  str-slice($string, 1, -3);

【讨论】:

  • 我显然没有想到这一点。一个方便的解决方案。不过我要指出,因为字符串不是在 Sass 中索引的 0,所以您的字符串切片实际上必须读取:str-slice($string, 2, -3); 以删除开头的 (。谢谢你。将很快标记为答案。如果有人能够进一步向我解释这个问题,我会很高兴。
  • 另外,您的输出看起来有些奇怪。首先,我不确定您是否需要为属性和值添加前缀(值应该足够了)。其次,就linear-gradient而言,我不确定它是否需要前缀:shouldiprefix.com/#gradientscaniuse.com/#search=linear-gradient——我可能是错的,如果是,请纠正!
  • shoudiprefix 说您不需要现代浏览器支持,但我正在尝试支持尽可能多的浏览器。 caniuse 表示供应商前缀确实支持更广泛的浏览器(即使它们很古老):caniuse.com/#search=linear-gradient
  • 这是有道理的。
猜你喜欢
  • 1970-01-01
  • 2013-11-25
  • 2015-09-21
  • 1970-01-01
  • 2018-05-29
  • 2019-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多