less实现if else

less没有我们平常使用的if,else条件判断,而是用when来实现这种用法

1.比如我们要设置宽度

宽度可以百分比,也可以是像素,当是百分比时做对应处理,当是px时做另一种处理,这时候就需要用when来实现if-else来实现条件判断

  • less语法实现if-else条件判断
@bs:20rem;//定义变量
//ispercentage是less中提供的方法,判断是不是百分比,返回bool值
.w(@width) when not(ispercentage(@width)){
//当不是百分比时(less中用的是not来表示非)
  width:@width/@bs;
} 
.w(@width) when (ispercentage(@width)){
//当是百分比时
  width:@width;
}
//less代码 测试
.container {
  width: 2.5rem;
}
.container-less {
  width: 50%;
}

 

//编译之后的css代码
.container {
  width: 2.5rem;
}
.container-less {
  width: 50%;
}

 

 

2.less有类似于c#语言的特点,方法的重载也就是可以定义多个重名方法,根据传递参数不同来识别对应方法调用


@bs:20rem; .w(@width) when not(ispercentage(@width)){ width:@width/@bs; } .w(@width) when (ispercentage(@width)){ width:@width; } .h(@height) when not(ispercentage(@height)){ height: @height/@bs; } .h(@height) when (ispercentage(@height)){ height:@height; } //定义多个同名方法position //只设置宽高的pos .pos(@width;@height)
{ .w(@width); .h(@height); position:absolute; } //设置宽高和url的pos .pos(@width;@height;@url){ .w(@width); .h(@height); position:absolute; background: url("../images/@{url}") no-repeat center/ 100% 100%; } //设置宽高,url和背景图片大小的pos .pos(@width;@height;@url;@pos1;@pos2){ .w(@width); .h(@height); position:absolute; background: url("../images/@{url}") no-repeat center/ @pos1/@bs @pos2/@bs; }
结果
 
.con1{
  .pos(30;50)
}
.con2{
  .pos(30;50;'page1/card1.png');
}
.con3{
  .pos(400;50%;'page1/card1.png';400;500)
}

 

 
.con1 {
  width: 1.5rem;
  height: 2.5rem;
  position: absolute;
}
.con2 {
  width: 1.5rem;
  height: 2.5rem;
  position: absolute;
  background: url("../images/page1/card1.png") no-repeat center / 100% 100%;
}
.con3 {
  width: 20rem;
  height: 50%;
  position: absolute;
  background: url("../images/page1/card1.png") no-repeat center / 20rem 25rem;
}

 

posted @ 2018-04-04 15:20  Dora Doris  阅读(1794)  评论(0编辑  收藏  举报