Less-Guard守卫

Guard翻译过来就是守卫的意思,在less中的作用就是给less的属性添加判断条件

less除了基本的计算还可以进行逻辑判断

使用when关键字来表示判断条件加载的逻辑,后面是判断条件依据

基本使用

.mixin(@width,@height) when (@width >= 100) {
  width: @width;
  height: @height;
}

.box{
  .mixin(100px,100px);
  background: red;
}

 

 上面的条件是当width大于等于100px的时候,再进行赋值

Less包含5个判断条件的运算符: > , < , >= , <=, =

.mixin(@width,@height) when (@width = 100) and (@height = @width) {
  width: @width;
  height: @height;
}

.box{
  .mixin(100px,100px);
  background: red;
}

 

 and表示并且的意思,就是逻辑与,相当于js中&&判断,组合起来就是when和and

.mixin(@width,@height) when (@width = 100) , (@height = 100) {
  width: @width;
  height: @height;
}

.box{
  .mixin(120px,100px);
  background: red;
}

 

 使用逗号来表示逻辑或,相当于js中的||判断,组合起来就是when和,

.mixin(@width,@height) when not (@width = 100) {
  width: @width;
  height: @height;
}

.box{
  .mixin(120px,100px);
  background: red;
}

使用not来表示逻辑非,相当于js中的!,组合起来就是when和not

 

 可以使用when结合函数来实现循环

// 判断条件是当cont 大于0 的时候,函数就调用自己(递归)
.cont(@cont) when(@cont > 0) {
  // 内部调用自己
  .cont(@cont - 1);
  width: (5px * @cont);
}

.box{
  .cont(5)
}

 

 上面的编译之后的代码是以5px为基数进行乘积,循环5次进行赋值

内部的判断条件还可以是内置函数

.mixin(@color) when(iscolor(@color)) {
  background: @color;
}

.box{
  width: 200px;
  height: 200px;
  .mixin(red)
}

 

 iscolor是less的内置函数,返回的是一个布尔值,如果布尔值为true了,则能赋值mixin内的属性

 

posted @ 2021-10-31 21:53  keyeking  阅读(52)  评论(0编辑  收藏  举报