首先来看如下的代码,一个 div 元素,分别设置了上下左右的宽度高度和颜色,然后在浏览器中打开发现四个不同的角都是一个小小的三角形如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>BNTang</title>
<style>
div {
width: 0;
height: 0;
border-width: 40px 40px 40px 40px;
border-style: solid solid solid solid;
border-color: #000 #f00 #0f0 #00f;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
这个时候你想要那个角的小三角你只需要把其它的小三角给设置为透明颜色即可如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>BNTang</title>
<style>
div {
width: 0;
height: 0;
border-width: 40px 40px 40px 40px;
border-style: solid solid solid solid;
border-color: #000 transparent transparent transparent;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
在企业开发当中会经常使用到像这样的小三角,所以这个时候是不是可以把它封装到一个混合当中
.triangle() {
width: 0;
height: 0;
border-width: 40px 40px 40px 40px;
border-style: solid solid solid solid;
border-color: #000 transparent transparent transparent;
}
div {
.triangle();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>BNTang</title>
<link rel="stylesheet" href="css/index.css">
</head>
<body>
<div></div>
</body>
</html>
以后你要是想要那个元素变为小三角形就直接调用一下如上的混合即可实现,现在封装的小三角的宽高颜色都是写死的,所以可以改造为让调用者传入
.triangle(@width, @color) {
width: 0;
height: 0;
border-width: @width;
border-style: solid solid solid solid;
border-color: @color transparent transparent transparent;
}
div {
.triangle(200px, blue);
}
如上封装的混合小三角只能实现向下,那么这个时候需要一个向上的小三角那该怎么办呢,复制如上的混合改一下方向?如下代码
.triangle(@width, @color) {
width: 0;
height: 0;
border-width: @width;
border-style: solid solid solid solid;
border-color: @color transparent transparent transparent;
}
.triangle(@width, @color) {
width: 0;
height: 0;
border-width: @width;
border-style: solid solid solid solid;
border-color: transparent transparent @color transparent;
}
div {
.triangle(200px, blue);
}
通过对如上代码的观察发现,后定义的小三角方法覆盖的线定义的,那么我向下的小三角不就是不能用了,那么这个时候就可以利用 less 中的混合的匹配模式来解决如上问题
就是通过混合的第一个字符串形参,来确定具体要执行哪一个同名混合
例如如下代码
.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(Down, 80px, green);
//.triangle(Top, 80px, green);
//.triangle(Left, 80px, green);
.triangle(Right, 80px, green);
}
@_
:表示通用的匹配模式
什么是通用的匹配模式
无论同名的哪一个混合被匹配了,都会先执行通用匹配模式中的代码 代码如上
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。