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 以外的任何值都是假的:

?

| 123 | .class``3``{``.truth(``40``); // 不会匹配到上面任何一个``} |

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

扫描二维码关注公众号,回复: 4383092 查看本文章
.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) { ... }

猜你喜欢

转载自blog.csdn.net/my_study_everyday/article/details/84829867
今日推荐