Sass中each、for、if的搭配使用


字数:432 阅读时长:2分钟 阅读:85

CSS 预处理器赋予了 CSS 逻辑编程的能力,其中 Sass、Less、Stylus 最受欢迎,语法都是大同小异,上手也很快。在项目中使用最多的可能要数 Sass 了,本文就讲讲 Sass 中循环遍历 @each@for@if 判断的搭配使用。

Sass && 循环遍历

语法示例

  • @for

@for 语法需要搭配 fromthrough 关键字使用,eg:

1
2
3
4
5
6
@for $index from 1 through 5 {
.box-bg-#{$index} {
background: url("../img/bg-#{$name}.png") no-repeat;
background-size: 100%;
}
}

编译后生成:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
.box-bg-1 {
background: url("../img/bg-1.png") no-repeat;
background-size: 100%;
}

.box-bg-2 {
background: url("../img/bg-2.png") no-repeat;
background-size: 100%;
}

.box-bg-3 {
background: url("../img/bg-3.png") no-repeat;
background-size: 100%;
}

.box-bg-4 {
background: url("../img/bg-4.png") no-repeat;
background-size: 100%;
}

.box-bg-5 {
background: url("../img/bg-5.png") no-repeat;
background-size: 100%;
}
  • @each

@each 语法需要 list 类似于 JSArray 数语的结构,可以先声明一个数组 list 变量,eg:

1
2
3
4
5
6
7
8
9
10
$states: 'before', 'ing', 'after';
@each $name in $states {
.box .#{$name} {
@if $name == 'after' {
$name: 'before'
}
background: url("../img/bg-#{$name}.png") no-repeat;
background-size: 100%;
}
}

编译后生成:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.box .before {
background: url("../img/bg-before.png") no-repeat;
background-size: 100%;
}

.box .ing {
background: url("../img/bg-ing.png") no-repeat;
background-size: 100%;
}

.box .after {
background: url("../img/bg-before.png") no-repeat;
background-size: 100%;
}

注意:

  • 其中做了一个 @if 判断,当变量 $name == 'after' 时,把变量赋值为 before
  • 当变量和字符串拼接时,一定要使用 #{$var} 的形式(类似ES6中的模板字符串),否则编译会报错。

欢迎访问:天问博客

本文作者: Tiven
发布时间: 2022-08-15
最后更新: 2022-08-16
本文标题: Sass中each、for、if的搭配使用
本文链接: https://www.tiven.cn/p/d5fe863/
版权声明: 本作品采用 CC BY-NC-SA 4.0 许可协议进行许可。转载请注明出处!
欢迎留言,提问 ^_^