7. Less 函数

本文介绍 less 中的常用函数,正是由于这些函数的存在,使得开发者能够更好的使用 less 这一强大的样式工具。熟悉并掌握这些函数能够让你在 less 的使用上更上一层楼!

less 中的函数大致可以分成 9 种:

  1. 其他函数。
  2. 字符串函数。
  3. 长度相关函数。
  4. 数学函数。
  5. 类型函数。
  6. 颜色值定义函数。
  7. 颜色值通道提取函数。
  8. 颜色值运算函数。
  9. 颜色混合函数。

下面具体的来看每个种类中的具体函数及用法。

1. 其他函数

下面展示 LESS 中 colorconvertdata-uridefaultunit 函数的基本用法。

1.1. color 函数

color 函数在 LESS 中用于从颜色字符串中提取颜色通道的值。

示例:

less 复制代码
@myColor: #123456;

.example {
  red-channel: red(@myColor);     // 提取红色通道值
  green-channel: green(@myColor); // 提取绿色通道值
  blue-channel: blue(@myColor);  // 提取蓝色通道值
  alpha-channel: alpha(@myColor); // 如果颜色包含透明度,则提取透明度值
}

编译后的 CSS:

css 复制代码
.example {
  red-channel: 18;
  green-channel: 52;
  blue-channel: 86;
  alpha-channel: 1;
}

1.2. convert 函数

convert 函数用于将数字从一种单位转换为另一种单位。

示例:

less 复制代码
@sizeInInches: 2in;

.example {
  size-in-cm: convert(@sizeInInches, cm); // 将英寸转换为厘米
}

编译后的 CSS:

css 复制代码
.example {
  size-in-cm: 5.08cm;
}

如果转换失败的话会照原样输出的:

less 复制代码
@sizeInInches: 2px;

.example {
  size-in-cm: convert(@sizeInInches, rem); // 将英寸转换为厘米
}

失败之后:

css 复制代码
.example {
  size-in-cm: 2px;
}

1.3. data-uri 函数

data-uri 函数用于将图片文件转换为 Base64 编码的 data URI,这样可以直接在 CSS 中嵌入图像,而不需要额外的 HTTP 请求。

示例:

less 复制代码
.example {
  background-image: data-uri('image.png'); // 假设 image.png 在相同目录下
}

编译后的 CSS:

css 复制代码
.example {
  background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...');
}

注意:data-uri 函数的具体输出取决于图片内容,这里只是一个简化的示例。

1.4. default 函数

default 函数用于检查一个变量是否有值,如果没有值则返回函数的第二个参数作为默认值。

示例 1 :

less 复制代码
.mixin(1)                   {x: 11}
.mixin(2)                   {y: 22}
.mixin(@x) when (default()) {z: @x}

div {
  .mixin(3);
}

div.special {
  .mixin(1);
}

编译后的 CSS:

css 复制代码
div {
  z: 3;
}
div.special {
  x: 11;
}

示例 2 :

less 复制代码
.mixin(@value) when (ispixel(@value)) {width: @value}
// .mixin(@value) when (default()) {padding-left: (@value / 5)}
.mixin(@value) when not(default()) {padding: (@value / 5)}


div-1 {
  .mixin(100px);
}

div-2 {
  /* ... */
  .mixin(100%);
}

编译后的 CSS:

css 复制代码
div-1 {
  width: 100px;
  padding: 20px;
}
div-2 {
  /* ... */
}

需要注意的是 when not(default())when (default()) 本身是互斥的,因此两个如果写在一起,一定会导致冲突。但是单独使用 when not(default())when (default()) 多次是可以的。

1.5. unit 函数

unit 函数用于移除或更改数字的单位。

示例:

less 复制代码
@size: 10px;

.example {
  no-unit: unit(@size);  // 移除单位
  new-unit: unit(@size, em); // 更改单位为 em
}

编译后的 CSS:

css 复制代码
.example {
  no-unit: 10;
  new-unit: 10em;
}

2. 字符串函数

下面通过示例代码来说明 LESS 中的 escapee%replaceunit 函数的作用和用法。

2.1 escape 函数

escape 函数用于对字符串中的特殊字符进行转义,以便能够在 CSS 中安全使用。

示例:

less 复制代码
@identifier: "hello#world";

.example {
  content: escape(@identifier); // 转义字符串中的特殊字符
}

编译后的 CSS:

css 复制代码
.example {
  content: hello%23world;
}

在这个例子中,# 被转义成了 %23

2.2 e 函数

e 函数用于对转义的字符串进行解码,它是 escape 函数的逆操作。

示例:

less 复制代码
@escapedString: "'hello.world'";

.example {
  content: e(@escapedString); // 解码转义的字符串
}

编译后的 CSS:

css 复制代码
.example {
  content: 'hello.world';
}

需要注意的是分号之间的嵌套关系。

2.2.1 e 函数的使用

有些计算需要让浏览器计算而不是让 less 计算,这个时候就可以使用 e 函数:

less 复制代码
div {
  width: calc(~'960px-100px');
}

这个时候 less 编译完的结果是:

css 复制代码
div {
  width: calc(960px-100px);
}

而不是由

less 复制代码
div {
  width: calc(960px-100px); // calc('960px-100px'); 本身是错误的
}

生成的

css 复制代码
div {
  width: calc(860px);
}

2.3 % 函数

函数 %(string, arguments ...) 格式化一个字符串。

第一个参数是带占位符的字符串. 所有占位符始于百分号%后跟字母s,S,d,D,a, or A. 剩下的参数是替换占位符的表达式. 如果你需要输出百分号, 用双百分号转义%%.

如果你需要把特殊字符转义成 utf-8转义码请使用大写字母占位符,该占位符会转义所有的特殊字符除了()'~!。空格会被转义成%20。小写字母占位符会保留特殊字符的原样。

占位符:

  • d, D, a, A 能被任何类型参数替换 (颜色值, 数字, 转义值, 表达式, ...). 如果你在字符串中结合使用, 整个字符串参数都会替换进去 - 包括它的引号. 然后, 然后引号会被替换到字符串参数的原有位置, 也许会被转义或者还是不变的,取决于占位符是大写字母还是小写字母。
  • s, S 能被除了颜色值以为任何类型参数替换. 如果你在字符串中结合使用, 只会替换成字符串参数的值,而字符串参数引号都被忽略。

参数:

  • string: 带占位符的格式化字符串,
  • anything* : 替换占位符的值。

返回: 格式化后的字符串 string

示例 1 :

less 复制代码
.example {
  format-a-d: %("repetitions: %a file: %d", 1 + 2, "directory/file.less");
  format-a-d-upper: %('repetitions: %A file: %D', 1 + 2, "directory/file.less");
  format-s: %("repetitions: %s file: %s", 1 + 2, "directory/file.less");
  format-s-upper: %('repetitions: %S file: %S', 1 + 2, "directory/file.less");
}

编译后的 CSS:

css 复制代码
.example {
  format-a-d: "repetitions: 3 file: "directory/file.less"";
  format-a-d-upper: 'repetitions: 3 file: %22directory%2Ffile.less%22';
  format-s: "repetitions: 3 file: directory/file.less";
  format-s-upper: 'repetitions: 3 file: directory%2Ffile.less';
}

示例 2 :

less 复制代码
.example {
  font-family: %("%a %a", "Microsoft", "YaHei");
}

.example2 {
  font-family: %("%A %A", "Microsoft", "YaHei");
}

.example3 {
  font-family: %("%s %s", "Microsoft", "YaHei");
}

编译后的 CSS:

css 复制代码
.example {
  font-family: ""Microsoft" "YaHei"";
}
.example2 {
  font-family: "%22Microsoft%22 %22YaHei%22";
}
.example3 {
  font-family: "Microsoft YaHei";
}

2.4 replace 函数

replace 函数用于在字符串中替换指定的子字符串。

示例:

less 复制代码
@string: "Hello, World!";

.example {
  content: replace(@string, "World", "LESS"); // 将 "World" 替换为 "LESS"
}

编译后的 CSS:

css 复制代码
.example {
  content: "Hello, LESS!";
}

2.5 unit 函数

unit 函数用于去除或更改数字的单位。

示例:

less 复制代码
@size: 10px;

.example {
  no-unit: unit(@size);  // 去除单位
  new-unit: unit(@size, em);   // 更改单位为 em
}

编译后的 CSS:

css 复制代码
.example {
  no-unit: 10;
  new-unit: 10em;
}

3. 长度相关的函数

3.1 length 函数

less 复制代码
.len {
  n: length(1px solid #FFF);
}

可以看出来,使用 length 可以清楚的知道当前的属性复合值到底由几部分组成。

length 函数多用于列表中,可以方便的得到列表的长度:

less 复制代码
@imgs: '1.png', '2.png', '3.png';
.len {
  n: length(@imgs);
}

3.2 extract 函数

这个函数用于获取序列中某个特定位置的值,其格式为:

less 复制代码
@imgs: '1.png', '2.png', '3.png';
@index: 2;
n: extract(@imgs, @index);

上述代码可使用 js 形象的表示为:

js 复制代码
const n = @imgs[@index];

4. 数学函数

以下是对 LESS 中这些数学函数的详细解释和示例:

  1. ceil函数 ceil 函数用于向上取整。

    less 复制代码
    @num: 4.7;
    .example {
      value: ceil(@num); // 输出 5
    }
  2. floor函数 floor 函数用于向下取整。

    less 复制代码
    @num: 4.7;
    .example {
      value: floor(@num); // 输出 4
    }
  3. percentage函数 percentage 函数将数字转换为百分比字符串。

    less 复制代码
    @num: 0.75;
    .example {
      value: percentage(@num); // 输出 75%
    }
  4. round函数 round 函数用于四舍五入到最接近的整数。

    less 复制代码
    @num: 4.7;
    .example {
      value: round(@num); // 输出 5
    }
  5. sqrt函数 sqrt 函数计算一个数的平方根。

    less 复制代码
    @num: 9;
    .example {
      value: sqrt(@num); // 输出 3
    }
  6. abs函数 abs 函数返回数字的绝对值。

    less 复制代码
    @num: -5;
    .example {
      value: abs(@num); // 输出 5
    }
  7. 三角函数(sin、cos、tan) sincostan 分别计算一个角度的正弦、余弦和正切值(角度以弧度为单位)。

    less 复制代码
    @angle: 45deg;
    .example {
      sin-value: sin(@angle);
      cos-value: cos(@angle);
      tan-value: tan(@angle);
    }
  8. 反三角函数(asin、acos、atan) asinacosatan 分别是正弦、余弦和正切的反函数,它们返回一个角度(以弧度为单位)。

    less 复制代码
    @value: 0.5;
    .example {
      asin-value: asin(@value);
      acos-value: acos(@value);
      atan-value: atan(@value);
    }
  9. pi函数 pi 函数返回圆周率的值。

    less 复制代码
    .example {
      pi-value: pi(); // 输出 3.141592653589793
    }
  10. pow函数 pow 函数返回底数的指数次幂。

    less 复制代码
    @base: 2;
    @exponent: 3;
    .example {
      pow-value: pow(@base, @exponent); // 输出 8
    }
  11. mod函数 mod 函数返回两数相除的余数。

    less 复制代码
    @dividend: 10;
    @divisor: 3;
    .example {
      mod-value: mod(@dividend, @divisor); // 输出 1
    }
  12. min函数和max函数 minmax 函数分别返回一组数中的最小值和最大值。

    less 复制代码
    @num1: 5;
    @num2: 10;
    @num3: 7;
    .example {
      min-value: min(@num1, @num2, @num3); // 输出 5
      max-value: max(@num1, @num2, @num3); // 输出 10
    }

请注意,这些函数的参数和返回值可能会根据 LESS 的版本和具体实现有所不同。此外,对于涉及角度的函数(如 sin, cos, tan, asin, acos, atan),LESS 可能需要将角度从度数转换为弧度,因此可能需要额外的函数或计算来进行转换。在上面的示例中,使用了 deg 后缀来表示角度,但在实际使用时,你可能需要根据 LESS 的版本和文档来确定正确的语法。

4.1 更多示例

示例 1 :

less 复制代码
.example {
  width: unit(sin(pi() / 2),px);
}

编译后的 CSS:

css 复制代码
.example {
  width: 1px;
}

示例 2 :

less 复制代码
@fontSize: 14px;
.example {
  width: pow(2px, 6);
  height: pow(16px, 0.5);
  line-height: mod(3px, 2);
  font-size: min(12px, @fontSize);
}

编译后的 CSS:

css 复制代码
.example {
  width: 64px;
  height: 4px;
  line-height: 1px;
  font-size: 12px;
}

5. 类型函数

类型函数是混合做重载的理想搭档。通过类型函数,我们可以根据输入值的不同单位做出不同的反应。再加上 default 函数和 Guard 表达式,就能够让混合成为完全体。

在 LESS 中,is* 函数系列用于检测某个值是否符合特定的类型或格式。下面对这些函数进行详细的解释:

  1. isnumber函数 isnumber 函数用于检测一个值是否为数字。

    less 复制代码
    @var1: 123;
    @var2: "text";
    
    .example {
      is-number-var1: isnumber(@var1); // 返回 true
      is-number-var2: isnumber(@var2); // 返回 false
    }

    编译结果为:

    css 复制代码
    .example {
       is-number-var1: true;
       is-number-var2: false;
     }
  2. isstring函数 isstring 函数用于检测一个值是否为字符串。

    less 复制代码
    @var1: "Hello, World!";
    @var2: 123;
    
    .example {
      is-string-var1: isstring(@var1); // 返回 true
      is-string-var2: isstring(@var2); // 返回 false
    }
  3. iscolor函数 iscolor 函数用于检测一个值是否为颜色值。

    less 复制代码
    @color1: #ff0000;
    @color2: rgb(0, 255, 0);
    @notColor: "red";
    
    .example {
      is-color1: iscolor(@color1); // 返回 true
      is-color2: iscolor(@color2); // 返回 true
      is-color3: iscolor(@notColor); // 返回 false
    }
  4. iskeyword函数 iskeyword 函数检测一个值是否为 CSS 关键字。

    less 复制代码
    @keyword: solid;
    @notKeyword: "solid";
    
    .example {
      is-keyword: iskeyword(@keyword); // 返回 true
      is-not-keyword: iskeyword(@notKeyword); // 返回 false
    }
  5. isurl函数 isurl 函数检测一个值是否为合法的 URL。

    less 复制代码
    @url: url('http://example.com');
    @notUrl: "http://example.com";
    
    .example {
      is-url: isurl(@url); // 返回 true
      is-not-url: isurl(@notUrl); // 返回 false
    }

    这里所说的 url 指的是被 url() 包裹的字符串而不是字符串本身。

  6. ispixel函数 ispixel 函数用于检测一个值是否以像素为单位(例如,10px)。

    less 复制代码
    @pixel: 10px;
    @notPixel: 10em;
    
    .example {
      is-pixel: ispixel(@pixel); // 返回 true
      is-not-pixel: ispixel(@notPixel); // 返回 false
    }
  7. isem函数 isem 函数检测一个值是否为 em 单位。

    less 复制代码
    @emValue: 10em;
    @notEm: 10px;
    
    .example {
      is-em: isem(@emValue); // 返回 true
      is-not-em: isem(@notEm); // 返回 false
    }
  8. ispercentage函数 ispercentage 函数检测一个值是否为百分比单位。

    less 复制代码
    @percentage: 50%;
    @notPercentage: 0.5;
    
    .example {
      is-percentage: ispercentage(@percentage); // 返回 true
      is-not-percentage: ispercentage(@notPercentage); // 返回 false
    }
  9. isunit函数 isunit 函数用于检测一个值是否包含单位(如 px, em, % 等)。注意,isunit 不是检测特定单位,而是检测值是否包含任何单位。

    less 复制代码
    @unitValue: 10px;
    @unitless: 10;
    
    .example {
      is-unit: isunit(@unitValue); // 返回 true
      is-not-unit: isunit(@unitless); // 返回 false
    }

请注意,isunit 函数与其他 is* 函数略有不同,因为它检测的是值是否带有任何单位,而不仅仅是特定的一个单位。

在编写 LESS 代码时,请确保你的 LESS 编译器版本支持这些函数,因为不同版本的 LESS 可能会有不同的函数支持和语法。如果你在使用这些函数时遇到问题,建议查阅你所使用的 LESS 版本的官方文档。

5.1 更多例子

iskeyword 函数本质上检测的内容就是除了 1 'abc' red 这样的正常属性值。比如

less 复制代码
.m(@x) when(iskeyword(@x)) {
    color: red;
}
.example {
  .m(ABC);
}

编译之后,

css 复制代码
.example {
  color: red;
}

6. 颜色函数

less 提供了相当复杂的颜色处理函数组,它们分别涉及颜色的定义提取运算混合。由于有些着实不常见,所以列举在这里等到用的时候再查询。

6.1 颜色定义函数

6.2 通道提取函数

6.3 颜色值运算函数

6.4 颜色混合函数

相关推荐
菩提小狗4 天前
Sqli-Labs Less-3 靶场完整解题流程解析-豆包生成
前端·css·less
cz追天之路14 天前
华为机考 ------ 识别有效的IP地址和掩码并进行分类统计
javascript·华为·typescript·node.js·ecmascript·less·css3
cz追天之路14 天前
华为机考--- 字符串最后一个单词的长度
javascript·css·华为·less
蜗牛攻城狮1 个月前
PostCSS 详解、最佳实践及其与 Less/SCSS 的关系
less·前端开发·postcss·scss
cc蒲公英1 个月前
less和sass区别
前端·less·sass
小明记账簿1 个月前
利用 Less 循环高效生成多组 CSS 间距工具类
前端·css·less
juma90021 个月前
基于 Xilinx K7 325t 的千兆网 UDP 协议实现小记
less
小书包酱1 个月前
告别在 vue 中使用公共 less 文件没有提示信息的烦恼
css·vue.js·less
abiao19812 个月前
VUE style标签中添加lang=less属性
前端·vue.js·less
IT从业者张某某2 个月前
less 工具 OpenHarmony PC适配实践
前端·microsoft·less