使用 Sass 默认参数的实用技巧

Avatar of Chris Coyier
Chris Coyier

DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 $200 免费积分!

Sass 提供接受 参数 的函数和 mixin。您可以使用 Sass 默认参数,即即使在调用函数或 mixin 时未提供值,这些参数也会具有值。

让我们在这里关注 mixin。这是 mixin 的语法

@mixin foo($a, $b, $c) {
  // I can use $a, $b, and $c in here, but there is a risk they are null
}

.el {
  @include foo(1, 2, 3);

  // if I tried to do `@include foo;`
  // ... which is valid syntax... 
  // I'd get `Error: Missing argument $a.` from Sass
}

在该 Sass mixin 中设置默认参数更安全,也更有用

@mixin foo($a: 1, $b: 2, $c: 3) {
}

.el {
  // Now this is fine
  @include foo;

  // AND I can send in params as well
  @include foo("three", "little", "pigs");
}

但是,如果我想传入 $b$c,但将 $a 作为 Sass 默认参数保留怎么办?诀窍是传入命名参数

@mixin foo($a: 1, $b: 2, $c: 3) {
}

.el {
  // Only sending in the second two params, $a will be the default.
  @include foo($b: 2, $c: 3);
}

使用 Sass 默认参数的真实示例

这是一个快速简便的 mixin,它输出非常基本的样式滚动条所需的内容(Kitty 也提供一个

@mixin scrollbars(
  $size: 10px,
  $foreground-color: #eee,
  $background-color: #333
) {
  // For Google Chrome
  &::-webkit-scrollbar {
    width: $size;
    height: $size;
  }
  &::-webkit-scrollbar-thumb {
    background: $foreground-color;
  }
  &::-webkit-scrollbar-track {
    background: $background-color;
  }

  // Standard version (Firefox only for now)
  scrollbar-color: $foreground-color $background-color;
}

现在我可以像这样调用它

.scrollable {
  @include scrollbars;
}

.thick-but-otherwise-default-scrollable {
  // I can skip $b and $c because they are second and third
  @include scrollbars(30px);
}

.custom-colors-scrollable {
  // I can skip the first param if all the others are named.
  @include scrollbars($foreground-color: orange, $background-color: black);
}

.totally-custom-scrollable {
  @include scrollbars(20px, red, black);
}

我只是在注意这一点,因为我不得不四处寻找才能弄清楚这一点。我尝试过一些方法,例如发送空字符串或 null 作为第一个参数以“跳过”它,但这不起作用。必须使用命名参数方法。