Less从入门到精通——条件表达式(附学习视频、源码及笔记)

完整学习视频及资料在这里哦~
连接:https://pan.baidu.com/s/1cXs9KKoIFP1M5oTClSr7yg
提取码:4k8thtml

条件表达式

  • 当须要根据表达式,而不是参数的值或数量来进行匹配时,就须要用到条件表达式了。
  • Less中使用关键字 when 来实现条件判断。
  • 表达式中能够使用比较运算符、逻辑运算符、或检查函数来进行条件判断。

比较运算符

有:>, >= , < , =< , = , ture;函数

.mixin(@width) when (@width <= 360px) {
    width: @width;
    height: 100%;
    background-color: pink;
}
.mixin(@width) when (@width > 360px) {
    width: @width;
    height: 100%;
    background-color: black;
}
div{
    .mixin(500px);
}
// 输出  匹配到第二个的条件 执行第二个
div {
  width: 500px;
  height: 100%;
  background-color: black;
}

还能够使用关键字true,它表示布尔真,如下两个mixin是相同的:学习

  • .truth (@a) when (@a) { ... }
  • .truth (@a) when (@a = true) { ... }

在Less中,只有 true 表示布尔真,关键字true之外的任何值,都被视为布尔假。如:url

.div{
    .truth(40);   	// 不会匹配上面的任何定义
}

注意:when后的条件表达式能够是多个表达式,多个表达式之间使用逗号相隔,若其中任何一个为true,则匹配为成功,至关于“ 或 ” 的关系。code

逻辑运算符

  • Less中,表达式之间也能够使用and 和 not 来进行逻辑运算。
  • and 链接的表达式需都为 true 才能匹配成功。
  • not 表示否认的意思 至关于“ 非 ”
// 传入的参数大于200px 且 小于 500px
.mixin(@width) when (@width > 200px) and (@width < 500px){
    width: @width;
    height: 100%;
    background-color: pink;
}
// 传入的参数 不小于500px 且 大于0
.mixin(@width) when not(@width < 500px) and (@width > 0){
    width: @width;
    height: 100%;
    background-color: black;
}
div{
    .mixin(500px);
}
// 输出为 匹配到第二个
div {
  width: 500px;
  height: 100%;
  background-color: black;
}

总结:逗号——或 , and——与 ,not——非。视频

类型检查函数

能够基于值的类型来匹配函数htm

类型检查函数 说明
iscolor 是否为颜色值
isnumber 是否为数值
isstring 是否为字符串
iskeyword 是否为关键字
isurl 是否为URL字符串

是则为 true 则执行匹配的内容,用于匹配相同的类型。blog

.mixin(@a) when (iscolor(@a)) {
    background-color: @a;
}
.mixin(@a) when (isnumber(@a)) {
    width: @a;
    height: @a;
}
div{
    .mixin(100%);
    .mixin(pink);
}
// 输出为 
div {
  width: 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)) {
    width: @a;
    height: @a;
}
div{
    .mixin(100%);
    .mixin(1px);
}
// 输出为
div {
  width: 100%;
  height: 100%;
  border: 1px solid pink;
}

参考博客:http://www.javashuo.com/article/p-dxcaxzyv-nx.htmlget

相关文章
相关标签/搜索