完整学习视频及资料在这里哦~
链接:https://pan.baidu.com/s/1XHxElnc2N-qwg2f2J30Qyw
提取码:4k8t
条件表达式
- 当需要根据表达式,而不是参数的值或数量来进行匹配时,就需要用到条件表达式了。
- Less中使用关键字
when
来实现条件判断。 - 表达式中可以使用比较运算符、逻辑运算符、或检查函数来进行条件判断。
比较运算符
有:>
, >=
,<
, =<
, =
, ture
;
.mixin(@width) when (@width <= 360px) {
@width;
height: 100%;
background-color: pink;
}
.mixin(@width) when (@width > 360px) {
@width;
height: 100%;
background-color: black;
}
div{
.mixin(500px);
}
// 输出 匹配到第二个的条件 执行第二个
div {
500px;
height: 100%;
background-color: black;
}
还可以使用关键字true
,它表示布尔真,例如以下两个mixin是相同的:
- .truth (@a) when (@a) { ... }
- .truth (@a) when (@a = true) { ... }
在Less中,只有 true
表示布尔真,关键字true以外的任何值,都被视为布尔假。如:
.div{
.truth(40); // 不会匹配上面的任何定义
}
注意
:when
后的条件表达式可以是多个表达式
,多个表达式之间使用逗号
相隔,若其中任何一个为 true
,则匹配为成功,相当于“ 或 ”
的关系。
逻辑运算符
- Less中,表达式之间也可以使用 and 和 not 来进行逻辑运算。
- and 连接的表达式需都为 true 才能匹配成功。
- not 表示否定的意思 相当于
“ 非 ”
// 传入的参数大于200px 且 小于 500px
.mixin(@width) when (@width > 200px) and (@width < 500px){
@width;
height: 100%;
background-color: pink;
}
// 传入的参数 不小于500px 且 大于0
.mixin(@width) when not(@width < 500px) and (@width > 0){
@width;
height: 100%;
background-color: black;
}
div{
.mixin(500px);
}
// 输出为 匹配到第二个
div {
500px;
height: 100%;
background-color: black;
}
总结:逗号——或 , and——与 ,not——非。
类型检查函数
可以基于值的类型来匹配函数
类型检查函数 | 说明 |
---|---|
iscolor | 是否为颜色值 |
isnumber | 是否为数值 |
isstring | 是否为字符串 |
iskeyword | 是否为关键字 |
isurl | 是否为URL字符串 |
以上若为是,则为 true , 则执行匹配的内容,用于匹配相同的类型 。 |
.mixin(@a) when (iscolor(@a)) {
background-color: @a;
}
.mixin(@a) when (isnumber(@a)) {
@a;
height: @a;
}
div{
.mixin(100%);
.mixin(pink);
}
// 输出为
div {
100%;
height: 100%;
background-color: pink;
}
单位检查函数
单位检查函数 | 说明 |
---|---|
ispixel | 是否为像素单位 |
ispercentage | 是否为百分比 |
isem | 是否为em单位 |
isunit | 是否为单位 |
同类型检查函数,用于匹配相同的单位 。 |
.mixin(@a) when (ispixel(@a)) {
border: @a solid pink;
}
.mixin(@a) when (ispercentage(@a)) {
@a;
height: @a;
}
div{
.mixin(100%);
.mixin(1px);
}
// 输出为
div {
100%;
height: 100%;
border: 1px solid pink;
}