zoukankan      html  css  js  c++  java
  • less新手入门(四)—— Mixin Guards

    八、Mixin Guards
    • 有条件的 mixin

    当您想要匹配表达式时,相对于简单的值或特性,Guards是有用的。如果您熟悉函数式编程,您可能已经遇到过它们。

    为了尽可能地保持CSS的声明性质,在@ media查询特性规则中,Less选择通过保护的mixin而不是if/ elsestatements 来执行条件执行。

    .mixin (@a) when (lightness(@a) >= 50%){
        background-color: black;
    }
    
    .mixin(@a) when (lightness(@a) < 50%){
        background-color: white;
    }
    
    .mixin(@a){
        color: @a;
    }

    关键字是when关键字,它引入了一个守卫序列(这里只有一个guard)。现在,如果我们运行以下代码:

    .class1 { .mixin(#ddd) }
    .class2 { .mixin(#555) }

    输出:

    .class1 {
      background-color: black;
      color: #ddd;
    }
    .class2 {
      background-color: white;
      color: #555;
    }

    8.1 guard 比较运算符

    在guard 可用的比较操作符的完整列表为:>、> =、=、<、<、<。另外,关键字true是唯一的truthy值,判断是否这两个参数值相等:

    .truth(@a) when (@a){ 
        font-size: 12px;
    }
    
    .truth(@a) when (@a = true){
        font-size: 26px;
    }

     

    除了关键字 true 以外的任何值都是假的:

    .class3{
        .truth(40);  // 不会匹配到上面任何一个
    }
    

    守卫可以用逗号分开,如果任何一个判断语句的计算结果为真,它被认为是一种匹配:

    .mixin (@a) when (@a > 10), (@a < -10) { ... }

     注意,您还可以比较彼此的参数,或者用非参数进行比较

    @media: mobile;
    
    .mixin (@a) when (@media = mobile) { ... }
    .mixin (@a) when (@media = desktop) { ... }
    
    .max (@a; @b) when (@a > @b) { width: @a }
    .max (@a; @b) when (@a < @b) { width: @b }

     

    8.2 类型检查功能

    最后,如果想要根据值的类型来匹配mixin,可以使用is函数

    .mixin (@a; @b: 0) when (isnumber(@b)) { ... }
    .mixin (@a; @b: black) when (iscolor(@b)) { ... }

    下面是一些基本类型检查函数:

    • iscolor
    • isnumber
    • isstring
    • iskeyword
    • isurl

    如果您想要检查一个值是否在一个特定的单元中,除了作为一个数字之外,您可以使用其中一个:

    • ispixel
    • ispercentage
    • isem
    • isunit

    8.3 有条件的混合

    此外,default  函数可以用于根据其他混合匹配创建mixin匹配,您可以使用它来创建类似于else或default语句的“条件混合”(if和case结构)。

    .mixin (@a) when (@a > 0) { ...  }
    .mixin (@a) when (default()) { ... } // matches only if first mixin does not, i.e. when @a <= 0

    最后但并非最不重要的是,您可以使用 and 关键字来为一个警卫提供额外的条件:

    .mixin (@a) when (isnumber(@a)) and (@a > 0) { ... }

    最后,not 关键字的否定条件:

    .mixin (@b) when not (@b > 0) { ... }

     

  • 相关阅读:
    Laravel 禁用指定 URL POST 请求的 csrf 检查
    laravel console
    python之面向对象(一)
    python中os.popen, os.system()区别
    Day6作业:计算器
    Day5作业,商城+ATM机+后台管理
    python基础之反射
    python基础之坑爹正则表达式
    python基础之模块(一)
    python 中的一些基础算法:递归/冒泡/选择/插入
  • 原文地址:https://www.cnblogs.com/fighxp/p/8080241.html
Copyright © 2011-2022 走看看