Mixin-和-CSS-Guards

12次阅读

共计 1315 个字符,预计需要花费 4 分钟才能阅读完成。

当我们想在表达式上进行匹配简单的值或者是参数数量时,我们可以使用 Guards;它与 mixin 声明相关联,并包括附加到 mixin 的条件。每个 mixin 将有一个或多个由逗号分隔的防护,并且 guard 必须括在括号中。

为了尽量接近 CSS 的声明性,Less 选择了使用通过受保护的 Guards 的 mixins 而不是 if / else 语句执行,并执行计算以指定匹配的 mixin。

Guard 比较运算符

Guards 中可用的比较运算符的完整列表为:>>===<<,此外关键字 true 是唯一的真实值,使这两个 mixin 等价。

    .compare (@a) when (@a) {...}
    .compare (@a) when (@a = true) {...}
    
    // 除关键字以外的任何值 true 都是伪造的
    .xkd{.compare(40);
    }
    
    // 可以将参数相互比较或与非参数进行比较
    @media: mobile;
    .mixin (@x) when (@media = mobile) {...}
    .mixin (@x) when (@media = desktop) {...}
    .max (@x; @y) when (@x > @y) {width: @x}
    .max (@x; @y) when (@x < @y) {width: @y}

Guard 逻辑运算符

可以将逻辑运算符与防护一起使用,语法基于 CSS 媒体查询。

    // 1: 使用 and 关键字来组合保护
    .mixin (@x) when (isnumber(@x)) and (@x > 0) {...}
    
    // 2: 通过用逗号分隔保护来模拟或运算符,如果任何一个守卫评估为 true,则认为是匹配
    .mixin (@x) when (@x > 10), (@x < -20) {...}
    
    // 3: 使用 not 关键字否定条件
    .mixin (@y) when not (@y > 0) {...}

类型检查函数

如果要根据值类型匹配混合,那么我们可以使用 is 功能。

    .mixin (@x; @y: 0) when (isnumber(@y)) {...}
    .mixin (@x; @y: black) when (iscolor(@y)) {...}

基本的类型检查功能:

  • iscolor
  • isnumber
  • isstring
  • iskeyword
  • isurl

如果要检查值是否是数字,是否还使用特定单位,则可以使用以下方法之一:

  • ispixel
  • ispercentage
  • isem
  • isunit

条件混合

(fixme)另外,默认函数可用于根据其他混合匹配进行混合匹配,并且我们可以使用它创建类似于 else 或默认语句(分别是 if 和 case 结构)的条件混合。

    .mixin (@x) when (@x > 0) {...}
    // 仅当第一个 mixin 不匹配时匹配,即当 @x<= 0 时
    .mixin (@x) when (default()) {...} 

CSS Guards

保护也可以应用于 css 选择器,这是声明 mixin 然后立即调用它的语法糖。

  • 直接将保护应用于样式

        button when (@mystyle = true) {color: white;}
  • if 通过将其与 & feature 结合使用来实现 if-type 语句,从而允许我们对多个防护进行分组。

        & when (@mystyle = true) {
          button {color: white;}
          a {color: green;}
        }

正文完
 0