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


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

    Sass && 循环遍历

    语法示例

    • @for

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

    @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

    编译后生成:

    .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%;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • @each

    @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%;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    编译后生成:

    .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%;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    注意:

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

    欢迎访问:天问博客

  • 相关阅读:
    Flutter:getX的学习
    基于FTP协议的文件上传与下载
    系统移植 DAY4(FSMP1A开发板开发阶段部署)
    three.js 第五十五用 给shader传递uniform注意事项
    JavaScript基础 JavaScript第五天 1. 对象
    Java泛型详解,史上最全图文详解!
    vue3 搭配ElementPlus做基础表单校验 自定义表单校验
    pytorch,numpy两种方法实现nms类间+类内
    linux安装mysql
    使用Redis优化Java应用的性能
  • 原文地址:https://blog.csdn.net/tiven_/article/details/126352869