less新手入门(四)—— Mixin Guards
2024-09-05 07:36:44
八、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) { ... }
最新文章
- C#递归遍历子目录与子目录中的文件
- HTTP 的重定向301,302,303,307(转)
- Strategy pattern策略模式
- stringstream操纵string小总结
- css兼容问题集合
- apktool更新,JDK升级配置
- solrcloud使用中遇到的问题及解决方式
- 快速替换dll命名空间
- Android端通过HttpURLConnection上传文件到服务器
- one problem about Apple Keychain in use
- SSD: Single Shot MultiBox Detector
- uitextfield银行卡加空格
- 可扩展标记语言XML
- angular.js封装的文件上传指令
- HTML5中的输入框
- 《UnityShader入门精要》学习笔记之渲染流水线
- linux时间格式总结
- MT【101】分配问题举例若干
- windows CIFS sabma协议识别
- item style edit in sharepoint 2013