在SASS参数面前散列

时间:2016-06-15 08:00:47

标签: css sass

我想知道之间的区别是什么:

@mixin transition($args...) {
  -webkit-transition: $args;
  -moz-transition: $args;
  -ms-transition: $args;
  -o-transition: $args;
  transition: $args;
}

@mixin transition($args...) {
  -webkit-transition: #{$args};
  -moz-transition: #{$args};
  -ms-transition: #{$args};
  -o-transition: #{$args};
  transition: #{$args};
}

在论证前加上#的目的是什么?

2 个答案:

答案 0 :(得分:4)

#{}语法会将花括号中的值插入到字符串中。例如,在以下情况下,当您的变量仅构成字符串的一部分时,这很有用。例如:

@mixin background-image($directory) {
    background-image: /#{$directory}image.jpg;
}

通过这种方式,SASS解释器可以理解变量$directory的结束位置。

如果你这样做,编译器会感到困惑:

@mixin background-image($directory) {
    background-image: $directoryimage.jpg;
}

在您给出的示例中,不需要它。两个版本都会产生相同的结果。

您也可以在mixins之外执行此操作。使用for循环考虑此示例:

@for $i from 1 through 3 {
  .item-#{$i} { width: 2em * $i; }
}

哪会产生:

.item-1 { width: 2em; }
.item-2 { width: 4em; }
.item-3 { width: 6em; }

答案 1 :(得分:0)

SASS中的#{}语法用于转义字符串。可能在你的例子中,除非你表现得非常复杂,否则它不会真正有用。

通常你会使用escape#符号来变量属性的名称。例如,仅使用列表自动创建一系列主题:

$themes: theme1, theme2, theme3;
$colors: red, blue, green;

@mixin colorTheme($keyColor) {
  color: nth($colors, $keyColor);
}

@each $theme in $themes {
  .class-#{$theme} {
    @include colorTheme(index($themes, $theme));
  }
}

将编译为:

.class-theme1 {
  color: red;
}

.class-theme2 {
  color: blue;
}

.class-theme3 {
  color: green;
}