less循环及函数使用
前言
当时项目使用element库,版本UI样式需要根据按钮(鼠标滑过、按钮获取焦点、禁用)状态展示对应状态的图标,当时使用的是复制粘贴同样代码,但只有class名和图标名称不一样
一、使用步骤
1.修改style标签
代码如下(示例):
<style lang="less" scoped></style>
2.函数封装、定义变量
定义变量:
class集合数组:
@classTypes: verify, edit, check;
定义函数:
.backgroundIcon(@className) {
/deep/.@{className}-button {
&:hover, &:focus {
&::after {
background: url('../../../../assets/edit/@{className}-focus.png');
background-size: 100% 100%;
}
}
}
}
定义循环:
循环记得调用
.loop(@i) when(@i < length(@classTypes) + 1) {
.backgroundIcon(extract(@classTypes, @i));
.loop(@i+1);
}
.loop(1);
编译后:
/deep/.verify-button {
&:hover, &:focus {
&::after {
background: url('../../../../assets/edit/verify-focus.png');
background-size: 100% 100%;
}
}
}
/deep/.edit-button {
&:hover, &:focus {
&::after {
background: url('../../../../assets/edit/edit-focus.png');
background-size: 100% 100%;
}
}
}
/deep/.check-button {
&:hover, &:focus {
&::after {
background: url('../../../../assets/edit/check-focus.png');
background-size: 100% 100%;
}
}
}