大前端

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

2022-08-15  本文已影响0人  天問_专注于大前端技术

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

Sass && 循环遍历

语法示例

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

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

编译后生成:

.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 语法需要 list 类似于 JSArray 数语的结构,可以先声明一个数组 list 变量,eg:

$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%;
    }
}

编译后生成:

.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%;
}

注意:


欢迎访问:天问博客

上一篇 下一篇

猜你喜欢

热点阅读