Scss创建三角形函数练习
最近深入学习了Scss语法,记录下通过函数方式创建通用三角形的方法
一、占位符选择器创建公共样式
// 提取三角形公共样式
%triangle-base {
display: inline-block;
width: 0;
height: 0;
}
二、mixin创建核心代码
@mixin triangle($direction: top, $size: 30px, $border-color: #000) {
// 通过占位符选择器继承公共样式
@extend %triangle-base;
// 统一设置四周边框
border: $size dashed transparent;
// 反转获取三角形对边名称
$reverse-direction: bottom;
@if ($direction == right) {
$reverse-direction: left;
}
@else if ($direction == bottom) {
$reverse-direction: top;
}
@else if ($direction == left) {
$reverse-direction: right;
}
border-#{$direction}-width: 0;
border-#{$reverse-direction}-style: solid;
border-#{$reverse-direction}-color: $border-color;
}
3、创建测试用例
// 创建测试用例
$triangle-list: (
"top": (
"direction": top,
"size": 20px,
"color": red,
),
"right": (
"direction": right,
"size": 30px,
"color": yellow,
),
"bottom": (
"direction": bottom,
"size": 40px,
"color": blue,
),
"left": (
"direction": left,
"size": 50px,
"color": black,
),
);
4、通过for循环测试用例
// 通过for循环测试用例
@for $i from 1 through 4 {
// 根据位置(注意不是下标),获取direction
$direction: nth(map-keys($triangle-list), $i);
.t#{$i} {
@include triangle(
map-get($triangle-list, $direction, "direction"),
map-get($triangle-list, $direction, "size"),
map-get($triangle-list, $direction, "color")
);
}
}
5、生成效果
.t4, .t3, .t2, .t1 {
display: inline-block;
width: 0;
height: 0;
}
.t1 {
border: 20px dashed transparent;
border-top-width: 0;
border-bottom-style: solid;
border-bottom-color: red;
}
.t2 {
border: 30px dashed transparent;
border-right-width: 0;
border-left-style: solid;
border-left-color: yellow;
}
.t3 {
border: 40px dashed transparent;
border-bottom-width: 0;
border-top-style: solid;
border-top-color: blue;
}
.t4 {
border: 50px dashed transparent;
border-left-width: 0;
border-right-style: solid;
border-right-color: black;
}/*# sourceMappingURL=func.css.map */
总结
通过函数方式的练习,感觉已经掌握了SCSS大部分语法了