less的mixin

less的官网:http://lesscss.org/

使用node下载less:

npm install -g less

编译less文件:

lessc styles.less styles.css

css有什么问题,为什么要使用预编译的less?

因为样式庞大以后,层次不清晰,它不像html一样有树状的文档结构,我们总是会找:谁谁谁的父类选择器是谁,css样式表会很乱。


如何使用less?

先写less文件,然后用命令行lessc命令编译成css文件,html中引入css的方式是外部引入(浏览器读的永远是css,而不是less,less方便程序员阅读和写)。


less的mixin

mixin翻译过来就是混合,它类似于函数,可以传参,可以调用。

现在有一段代码,可以画出一个三角形:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<!--<link rel="stylesheet" type="text/css" href="css/css02.css" />-->
		<style type="text/css">
			#wrap .sjx {
				width: 0;
				height: 0;
				border-style: solid;
				border-width: 60px;
				border-color: transparent transparent transparent green;
			}
		</style>
	</head>

	<body>
		<div id="wrap">
			<div class="sjx">

			</div>
		</div>
	</body>

</html>


现在我们使用外部引入:

<link rel="stylesheet" type="text/css" href="css/css02.css" />

然后我们编写less文件:

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

#wrap .sjx {
    .triangle(60px, yellow);
}

这里的.triangle就是一个mixin,它被选择器调用了。而且这里的border-width和border-color是动态传入的。

编译后的css文件为:

#wrap .sjx {
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 60px;
  border-color: transparent transparent transparent yellow;
}

这和我们直接写是一样的。


@import

.triangle的代码甚至可以提出来,就像一个写好的外部接口一样,我们把它放入mode_match.less文件中,然后使用外部引用的方式导入:

@import "mode_match.less";

less中的模式匹配

现在真正的代码就是

@import "mode_match.less";

#wrap .sjx {
    .triangle(60px, yellow);
}

我们能做的就是丰富外部接口.triangle。

比如有这么一个需求:

根据传入的参数不同,三角形的朝向不同。

所以,我们要把朝向作为一个参数传入混合。

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

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

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

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

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

less文件中写多一点是没有问题的,因为它就是预编译的,我们会编译好,然后再在运行时给浏览器读css。

因为width,height,border-style都是重复代码,所以把它给抽取出来了,其他的三个混合,都传入了一个匹配的模式,即L,R,T,B。

调用的时候这么调:

@import "mode_match.less";

#wrap .sjx {
    .triangle(B,80px, red);
}

看看编译后的css:

#wrap .sjx {
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 80px;
  border-color: red transparent transparent transparent;
}

也就是先调抽取出来的方法,再调特有的方法。

发布了25 篇原创文章 · 获赞 26 · 访问量 1138

猜你喜欢

转载自blog.csdn.net/weixin_43810802/article/details/104021493