6_less中的匹配模式

如果利用div创建一个箭头:

它的HTML代码:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="stylesheet/less" href="css/09.less">
    <script src="js/less.js"></script>
</head>
<body>
<div></div>
</body>
</html>

它的less代码:

.triangle(@width,@color) {
  width: 0;
  height: 0;
  border-style: solid solid solid solid;
}

div {
  .triangle(80px, blue);
}

如果要创建不同朝向的这个箭头,
此时可以利用less的匹配:

.triangle(Down,@width,@color) {
  width: 0;
  height: 0;
  border-width: @width;
  border-style: solid solid solid solid;
  border-color: @color transparent transparent transparent;
}

.triangle(Top,@width,@color) {
  width: 0;
  height: 0;
  border-width: @width;
  border-style: solid solid solid solid;
  border-color: transparent transparent @color transparent;
}

.triangle(Left,@width,@color) {
  width: 0;
  height: 0;
  border-width: @width;
  border-style: solid solid solid solid;
  border-color: transparent @color transparent transparent;
}

.triangle(Right,@width,@color) {
  width: 0;
  height: 0;
  border-width: @width;
  border-style: solid solid solid solid;
  border-color: transparent transparent transparent @color;
}

div {
// 此时利用第一个形参,指定调用上面第四个 .triangle
  .triangle(Right, 80px, blue);
}

运行:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2Xdm9RDo-1607182203842)(img/7.png)]

但是,此时可以发现,有好多重复的代码:

  width: 0;
  height: 0;
  border-style: solid solid solid solid;

所以,此时可以用通用匹配模式:

// 表示是要调用了这个 triangle ,就会执行里面的代码
.triangle(@_,@width,@color) {
  width: 0;
  height: 0;
  border-style: solid solid solid solid;
}

那么,less代码最终可以简化为:

// @_ 表示匹配所有,只要调用了triangle,就会调用有 @_ 的样式
// @_ 表示通用的匹配模式
// 什么是通用匹配模式:
// 就是无论哪一个混合被匹配了,都会执行通用匹配模式中的代码
.triangle(@_,@width,@color) {
  width: 0;
  height: 0;
  border-style: solid solid solid solid;
}

.triangle(Down,@width,@color) {
  border-width: @width;
  border-color: @color transparent transparent transparent;
}

.triangle(Top,@width,@color) {
  border-width: @width;
  border-color: transparent transparent @color transparent;
}

.triangle(Left,@width,@color) {
  border-width: @width;
  border-color: transparent @color transparent transparent;
}

.triangle(Right,@width,@color) {
  border-width: @width;
  border-color: transparent transparent transparent @color;
}

div {
  .triangle(Left, 80px, blue);
}

让代码短了一丢丢

全部评论

相关推荐

10-22 15:25
门头沟学院 C++
种花网友小松:求求你别发了,我几乎都快嫉妒得疯了,倒在床上蒙住被子就开始抱着枕头尖叫流泪,嘴里一边喊着卧槽卧槽,一边又忍着,我边发边哭,打字的手都是抖的,后来我的手抖得越来越厉害,从心头涌起的思想、情怀和梦想,这份歆羡和悔恨交织在一起,我的笑还挂在脸上,可是眼泪一下子就掉下来了。求你了别发了,我生活再难再穷我都不会觉得难过,只有你们发这种东西的时候,我的心里像被刀割一样的痛,打着字泪水就忍不住的往下流。
我的求职进度条
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务