SASS函数

本文介绍了SASS函数。

我们将从基础到高级全面讲解SASS函数,包括实际工作中有用的实用示例。

YouTube Video

SASS函数

SASS函数是在样式表中封装可复用逻辑的强大工具,可以实现计算、格式化和条件分支。

函数的基本结构与用法

SASS函数使用@function定义,并通过@return返回值。函数的调用方式与内置函数相同。

1// Example: Define a simple function that doubles a value
2@function double($n) {
3  @return $n * 2;
4}
5
6// Use the function
7.example {
8  width: double(10px);  // -> 20px
9}
  • 此代码定义了一个函数,将数字加倍并应用到宽度上。因此会生成.example { width: 20px; }

参数、默认值与类型处理

函数可以接受多个参数并设置默认值。SASS不强制静态类型,但注意参数格式可以让你的函数更健壮。

1// Example: Function with default parameters
2@function responsive-font($base-size, $scale: 1.2, $unit: px) {
3  @return $base-size * $scale + $unit;
4}
5
6.title {
7  font-size: responsive-font(16, 1.25);  // -> 20px
8}
  • responsive-fontscaleunit设有默认值,调用时可以省略部分参数。在此示例中,将输出类似 font-size: 20px; 的值。

可变参数的使用(...

如果需要传递多个值,可以使用可变参数。这在处理列表或多种颜色时非常有用。

 1// Example: Sum any number of numbers passed in
 2@function sum-all($numbers...) {
 3  $total: 0;
 4  @each $n in $numbers {
 5    $total: $total + $n;
 6  }
 7  @return $total;
 8}
 9
10.box {
11  padding: sum-all(4px, 6px, 10px);  // -> 20px
12}
  • $numbers...这样的可变参数会被当作列表处理,并可使用@each进行遍历。在此示例中,将输出 padding: 20px;

返回与操作列表或映射(map)

函数同样可以返回列表(用空格或逗号分隔)和映射。这对于返回复杂值很有用。

 1@use "sass:map";
 2
 3// Example: Return a map of spacing scale
 4@function spacing-scale($base) {
 5  @return (
 6    'small': $base * 0.5,
 7    'medium': $base,
 8    'large': $base * 2
 9  );
10}
11
12$scale: spacing-scale(8px);
13
14.card {
15  margin-bottom: map.get($scale, 'medium');
16}
  • 函数返回一个映射(map),然后可以用 map.get 获取值。这样可以保持统一的间距系统。

包含条件和循环的函数

@if@else if@else@for@each@while都可以在函数中使用。你可以用条件和循环创建计算逻辑。

 1// Example: Generate modular scale value using loop
 2@function modular-scale($step, $base: 1rem, $ratio: 1.25) {
 3  $result: $base;
 4  @if $step == 0 {
 5    @return $result;
 6  }
 7  @if $step > 0 {
 8    @for $i from 1 through $step {
 9      $result: $result * $ratio;
10    }
11  } @else {
12    @for $i from 1 through abs($step) {
13      $result: $result / $ratio;
14    }
15  }
16  @return $result;
17}
18
19.h1 {
20  font-size: modular-scale(3, 1rem, 1.333);
21}
  • 该函数根据步进的正负实现模度比例的乘法或除法计算。modular-scale(3, 1rem, 1.333)返回比基准大三步的字体大小。

错误处理与警告(@error@warn

当参数无效或操作异常时,可以用@error终止,也可以用@warn发出警告。这样可以及早提醒用户发现问题。

 1@use "sass:math";
 2@use "sass:meta";
 3
 4// Example: Validate input and throw an error for invalid units
 5@function ensure-length($value) {
 6  @if meta.type-of($value) != 'number' or math.is-unitless($value) {
 7    @error "Expected a length with units, got #{$value}.";
 8  }
 9  @return $value;
10}
11
12// Valid input (should pass)
13.test-valid {
14  width: ensure-length(10px); // expect: 10px
15}
16
17// Invalid input (should throw error during compilation)
18// Uncomment the following to test error handling:
19//
20// .test-invalid {
21//   // expect error: "Expected a length with units, got 10."
22//   width: ensure-length(10);
23// }
  • 如果传入无效值,编译时会输出错误,便于找出原因。在函数内部进行检查有助于及早发现错误。

创建与颜色相关的专用函数

在 SASS 中,你可以结合各种操作颜色的函数来创建自己的配色方案。这对于在整个项目中管理统一的色彩方案非常有用。

 1@use "sass:color";
 2@use "sass:list";
 3
 4// Example: Generate a color palette (tints and shades) from a base color
 5@function palette($color, $steps: 5, $strength: 10%) {
 6  $colors: ();
 7  @for $i from 0 through $steps {
 8    $amount: $i * $strength;
 9    $shade: if($i == 0, $color, color.mix(black, $color, $amount));
10    $tint: color.mix(white, $color, $amount);
11    $colors: list.append($colors, $shade);
12    $colors: list.append($colors, $tint);
13  }
14  @return $colors;
15}
16
17$palette: palette(#3498db, 3, 15%);
18
19.btn {
20  background-color: list.nth($palette, 1);
21}
  • 在这个例子中,color.mix 用于通过与黑色混合生成阴影,通过与白色混合生成浅色。值以列表形式返回,可以使用 list.nth 访问。

性能与编译时间注意事项

SASS函数在编译时进行计算。大量循环、深度递归或大规模映射操作会增加编译时间。尽量让函数精简;如有必要,复杂处理应交由构建工具或预处理器完成,而不放在SASS中。

实用工具函数集锦

以下是一些常用的工具函数。这些代码可以直接应用于实际项目。

 1@use "sass:math";
 2
 3// Example: Clamp a value between min and max
 4@function clamp-value($value, $min, $max) {
 5  @if $value < $min {
 6    @return $min;
 7  } @else if $value > $max {
 8    @return $max;
 9  }
10  @return $value;
11}
12
13// Example: Convert px to rem (with optional root size)
14@function px-to-rem($px, $root: 16px) {
15  @if math.unit($px) != "px" {
16    @error "px-to-rem requires a px value.";
17  }
18  @return ($px / $root) * 1rem;
19}
  • clamp-value 用于对值施加上下限,px-to-rem 用于将像素值转换为 rem。这两者都简化了响应式设计中常见的处理流程。

选择@function与混入(@mixin

函数专注于返回一个值,而混入用于输出CSS代码块。如果逻辑结果是单个属性值,用函数;如果是整个样式模块,用混入。

 1// Example: Function returns a value
 2@function border-radius-value($size) {
 3  @return $size * 1px;
 4}
 5
 6// Example: Mixin outputs properties
 7@mixin rounded($size) {
 8  border-radius: border-radius-value($size);
 9  -webkit-border-radius: border-radius-value($size);
10}
11.card {
12  @include rounded(8);
13}
  • 函数返回数字、颜色等数值,可供其它属性使用;混入直接插入一组样式属性。设计时严格区分可提高可维护性。

字符串处理与输出格式注意事项

在SASS中处理带单位的数字与字符串时要小心。将带单位数字与字符串拼接可能产生非预期的输出结果。可根据需要使用unquote()或字符串插值(#{})。

 1@use "sass:math";
 2
 3// Example: Safely create a CSS value string
 4@function px-percentage($px, $total) {
 5  $percent: math.div($px, $total) * 100;
 6  @return "#{$percent}%";
 7}
 8
 9// Safer with interpolation and math module
10@function px-percentage-safe($px, $total) {
11  $percent: math.div($px, $total) * 100;
12  // Round to 2 decimal places safely
13  $rounded: math.div(math.round($percent * 100), 100);
14  @return "#{$rounded}%";
15}
  • 返回百分比字符串时,建议用插值或round处理精度以保证结果清晰明了。为避免错误,拼接计算结果与字符串时一定要明确处理数据类型。

测试与文档编写的最佳实践

编写函数后,可制作带用例的小型SCSS文件做为测试,便于后续维护。你可以为每个函数记录输入类型/单位、返回类型、失败时表现和用例。

 1@use "sass:math";
 2
 3// Example: Inline "tests" (partial usage examples)
 4// These can be compiled separately during development
 5
 6@function double($n) {
 7  @return $n * 2;
 8}
 9
10@function px-to-rem($px, $root: 16px) {
11  @if math.unit($px) != "px" {
12    @error "px-to-rem requires a px value.";
13  }
14  @return math.div($px, $root) * 1rem;
15}
16
17// Test double()
18.test-double {
19  width: double(12px); // expect 24px
20}
21
22// Test px-to-rem()
23.test-rem {
24  font-size: px-to-rem(18px, 18px); // expect 1rem
25}
26
27// --- Inline debug tests ---
28@debug "double(12px) => #{double(12px)} (expect 24px)";
29@debug "px-to-rem(18px, 18px) => #{px-to-rem(18px, 18px)} (expect 1rem)";
  • 在注释中附带小型“期望输出”示例,能帮助日后重构时快速发现问题。在CI环境中自动编译并直观地核查输出结果十分有效。

总结

SASS函数是提升样式复用性和统一性的强大手段。应将其设计得精简易懂,并通过@error@warn保证安全性。颜色、间距及单位转换等工具函数建议统一整理到共享库。为避免编译负担,必要时可将复杂逻辑拆分至其他构建步骤。

您可以在我们的YouTube频道上使用Visual Studio Code跟随上述文章进行学习。 请也查看我们的YouTube频道。

YouTube Video