10

我正在创建一些在我的网站中使用的图标字体规则。使用 Sass,我想列出一个列表变量中的所有图标,并使用 @each 来遍历它们。

代码如下所示:

$icons: 
    wifi 600,
    wifi-hotspot 601,
    weather 602;

@each $icon in $icons {
    .icon-#{nth($icon, 1)}, 
    %icon-#{nth($icon, 1)} {
        content: "\#{nth($icon, 2)}";
    }
}

问题是该content:行的反斜杠。我需要它来进行字符编码,但它会转义变量插值,输出如下所示的 CSS:

.icon-wifi {
  content: "\#{nth($icon, 2)}";
}

像这样再添加一个反斜杠:content: "\\#{nth($icon, 2)}";输出这个 CSS:

.icon-wifi {
  content: "\\600";
}

有没有办法让 Sass 在保持变量插值的同时只用一个反斜杠输出 CSS?

4

6 回答 6

9

我通过弄乱插值来使它工作

萨斯迈斯特演示

// ----
// Sass (v3.4.21)
// Compass (v1.0.3)
// ----

$icons: 
    wifi 600,
    wifi-hotspot 601,
    weather 602;

@each $icon in $icons {
    .icon-#{nth($icon, 1)}, 
    %icon-#{nth($icon, 1)} {
        content: #{'"\\' + nth($icon, 2) + '"'}; // <------ See this line
    }
}

编译为

.icon-wifi {
  content: "\600";
}

.icon-wifi-hotspot {
  content: "\601";
}

.icon-weather {
  content: "\602";
}
于 2017-07-27T04:24:16.420 回答
7

如果在实际变量中包含反斜杠,那么sass在生成css时,实际上会生成计算出的unicode字符,而不是在css输出中输出unicode。这通常仍然有效,但如果出现问题,则很难调试,而且在呈现图标时更容易导致浏览器出现问题。

要在生成的 CSS 中输出实际的 unicode,您可以这样做:

@function icon($character){
    @return unquote('\"') + unquote(str-insert($character,'\\', 1)) + unquote('\"');
}

$icon-thing: "e60f";

.icon-thing:before {
    content: icon($icon-thing); //outputs content: "\e60f";
}
于 2016-03-07T00:52:19.537 回答
2

您可以将反斜杠添加到变量中的参数 $icons。那是,

$icons: wifi "\600", wifi-hotspot "\601", weather "\602";

@each $icon in $icons {
  .icon-#{nth($icon, 1)}, %icon-#{nth($icon, 1)} {
    content: "#{nth($icon, 2)}";
  }
}

生成的 CSS:

.icon-wifi {
  content: "\600"; 
}

.icon-wifi-hotspot {
  content: "\601"; 
}

.icon-weather {
  content: "\602"; 
}   
于 2014-02-06T16:56:35.600 回答
1

使用取消引号和双斜杠

$var:123 → 内容:"\e123"

 content:#{unquote('\"')+("\\")+("e")+$var+unquote('\"')};
于 2020-01-14T20:18:19.973 回答
0

如果你使用 Gulp 编译你的 Sass 文件,安装这个 Gulp 插件可能是解决这个问题的最简单方法:

https://www.npmjs.com/package/gulp-sass-unicode

var sass = require('gulp-sass');
var sassUnicode = require('gulp-sass-unicode');

gulp.task('sass', function(){
  gulp.src('style.scss')
    .pipe(sass())
    .pipe(sassUnicode()) // <-- This is the bit that does the magic
    .pipe(gulp.dest( "css/" ));
});

无需在 Sass 文件中进行任何代码更改。写出你想要的 Sass 代码,然后将 unicode 字符自动解码回输出 CSS 中的常规转义字符串。

输入 SCSS

$testContent: "\f26e";

#test {
  content:  $testContent;
}

输出 CSS

#test {
  content: "\f26e";
}
于 2018-10-06T04:13:04.713 回答
0

不幸的是,这些解决方案并不完全适合我,但我终于能够使用它SASS maps

//node-sass 4.11.0
//libsass 3.5.4

$hexes: (
           checkmark: \2714
        );

@function out-content($var) {
    @return unquote("\"#{ $var }\""); 
}

@each $mod, $code in $hexes {    
    .#{$mod}-after {
        &:after {
            content: out-content($code);
        }
    }
}

//output
//.checkmark-after:after {
    //content: "\2714";
//}
于 2019-02-07T19:51:12.467 回答