【问题标题】:Sass mixin that applies CSS hacks应用 CSS hack 的 Sass mixin
【发布时间】:2020-06-20 02:47:35
【问题描述】:

我正在尝试创建适用于不同浏览器的 CSS hack 的 mixin:

@mixin browsers($browsers) {
    $selectors: (
        chrome: '&:not(*:root)',
        firefox: '@-moz-document url-prefix()',
        ie: '@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none)'
    );

    @each $browser in $browsers {
        #{map-get($selectors, $browser)} {
            @content;
        }
    }
}

例如:

#test {
    @include browsers(firefox ie) {
        background: red;
    }
}

预期的编译输出是:

@-moz-document url-prefix() {
    #test {
        background: red;
    }
}
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
    #test {
        background: red;
    }
}

但它失败了:

Error: expected selector.

@-moz-document url-prefix(){
^

当然,我可以在 @each 中使用 if/else 语句,例如:

@if $browser == chrome {
    &:not(*:root) {
        @content;
    }
} @else if $browser == firefox {
    @-moz-document url-prefix() {
        @content;
    }
} @else if $browser == ie {
    @media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
        @content;
    }
}

但是否有可能做得更...优雅?

【问题讨论】:

  • 据我所知,你得到了你想要的。

标签: sass scss-mixins


【解决方案1】:

你忘记了一个逗号。

#test {
    @include browsers(firefox ie) {
        background: red;
    }
}

应该是

#test {
    @include browsers(firefox, ie) {
        background: red;
    }
}

【讨论】:

  • 不,firefox ie 正在解析为 $browsers 参数值。如您所见,@mixin browsers($browsers) 只得到一个参数,然后在@each 部分解析它。您的代码将返回编译错误,例如“参数数量错误(2 比 1)”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-15
  • 2019-04-29
  • 2019-10-27
  • 2021-10-29
  • 2014-06-23
  • 2013-03-14
  • 2011-10-31
相关资源
最近更新 更多