欢迎加入QQ讨论群258996829
麦子学院 头像
苹果6袋
6
麦子学院

Less的运算符和函数

发布时间:2016-07-22 22:48  回复:0  查看:2456   最后回复:2016-07-22 22:48  

今天给大家写一篇关于Less运算符和函数的less学习教程 ,有什么问题一起探讨。

 

运算符

  Less还支持+-*/运算符。但对单位不一致的运算数进行运算要注意以下两点:

  1. 运算数与运算符间必须用空格分隔;

  2. 以第一个运算数的单位作为运算结果的单位;

    Less源码:

 

// 运算数与运算符间没有空格

@fail: 1px +2em;

.fail{

  height: @fail;

}

 

@success1: 1px + 2em;

.success1{

  height: @success1;

}

 

@success2: 2px + 1em;

.success2{

  height: @success2;

}

 

    最终输出:

 

.fail{

  height: 1px 2em;

}

 

.success1{

  height: 3px;

}

 

.success2{

  height: 3em;

}

 

函数

  Less为我们提供了一个功能强大的内置函数库,其中绝大部分为颜色处理函数。下面着重介绍Misc Function中的default函数、String Function中的escape函数和颜色处理函数。

  1. default函数

     示例:

 

// for teenager

.person(@age) when (@age <= 19) and (@age >=13){

  height: @age * 10px;

}// for child

.person(@age) when (@age <13){

  height: @age * 6px;

}// for adult

.person(@age) when (default()){

  height: 180px;

}

 

.son{

  .person(10);

}

.daughter{

  person(17);

}

.father{

 .person(27);

}

    最终输出:

.son{

  height: 60px;

}

.daughter{

  height: 170px;

}

.father{

  height: 180px;

}

    虽然上述示例逻辑上不合理。但可以看出default函数用于条件控制当中,充当elseswitch语句中default的角色。

    通过官网提供的综合示例我们可以更好理解它的用法:

// Less源码.x {

  .m(red)                                    {case-1: darkred}

  .m(blue)                                   {case-2: darkblue}

  .m(@x) when (iscolor(@x)) and (default())  {default-color: @x}

  .m('foo')                                  {case-1: I am 'foo'}

  .m('bar')                                  {case-2: I am 'bar'}

  .m(@x) when (isstring(@x)) and (default()) {default-string: and I am the default}

 

  &-blue  {.m(blue)}

  &-green {.m(green)}

  &-foo   {.m('foo')}

  &-baz   {.m('baz')}

}

// 最终输出

.x-blue {

  case-2: #00008b;

}

.x-green {

  default-color: #008000;

}

.x-foo {

  case-1: I am 'foo';

}

.x-baz {

  default-string: and I am the default;

}

   注意:

     1. default函数必须在条件控制语句当中使用;

     2. default函数可实现比else更复杂的功能,如下:

// Less源码.mixin(@value) when (ispixel(@value)) {width: @value}

.mixin(@value) when not(default())    {padding: (@value / 5)}

 

div-1 {

  .mixin(100px);

}

 

div-2 {

  /* ... */

  .mixin(100%);

}

// 最终输出:

div-1 {

  width: 100px;

  padding: 20px;

}

div-2 {

  /* ... */

}

  2. escape函数

    顾名思义就是对字符串中的特定字符进行编码,该函数将对\<space\>, #, ^, (, ), {, }, |, :, >, <, ;, ], [  =字符进行编码。

  3. 颜色处理函数

    颜色处理函数又分为四大类:颜色定义函数(Color Definition)、颜色通道值获取函数(Color Channel)、颜色通道值修改函数(Color Operation Function)、混色函数(Color Blending)

    这里仅仅介绍常用的lightendarken函数。

     lighten(color, amount) color为颜色,amount为增加的亮度值,取值范围为0-100%

     darken(color, amount) color为颜色,amount为减少的亮度值,取值范围为0-100%

 

 

 

原文来自:博客园/张来秀

您还未登录,请先登录

热门帖子

最新帖子