Mixin 和 CSS Guards

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

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

Guard 比较运算符

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

.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媒体查询。code

// 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 功能。string

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

基本的类型检查功能:it

  • iscolor
  • isnumber
  • isstring
  • iskeyword
  • isurl

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

  • ispixel
  • ispercentage
  • isem
  • isunit

条件混合

(fixme)另外,默认函数可用于根据其余混合匹配进行混合匹配,而且咱们可使用它建立相似于else或默认语句(分别是if和case结构)的条件混合。css选择器

.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;
          }
        }
相关文章
相关标签/搜索