前端实用小技巧
今天分享一个前端常用的实用小技巧,在我们前端的开发过程中,经常会遇见一些 “三角形”,其实这些“三角形”完全可以不用找UI设计师要(除非是特殊定制的),不然都是可以用纯css实现的。接下来就用纯css实现各种方向的三角形
效果图
代码实现
<div class="triangle top-triangle"></div>
<div class="triangle right-triangle"></div>
<div class="triangle bottom-triangle"></div>
<div class="triangle left-triangle"></div>
.triangle {
margin-left: 16px;
}
.top-triangle {
width: 0;
height: 0;
border: 12px salmon solid;
border-radius: 4px;
border-top-color: transparent;
border-left-color: transparent;
border-right-color: transparent;
}
.right-triangle {
width: 0;
height: 0;
border: 12px seagreen solid;
border-radius: 4px;
border-top-color: transparent;
border-bottom-color: transparent;
border-right-color: transparent;
}
.bottom-triangle {
width: 0;
height: 0;
border: 12px slateblue solid;
border-radius: 4px;
border-bottom-color: transparent;
border-left-color: transparent;
border-right-color: transparent;
}
.left-triangle {
width: 0;
height: 0;
border: 12px skyblue solid;
border-radius: 4px;
border-top-color: transparent;
border-bottom-color: transparent;
border-left-color: transparent;
}
以上便是使用纯css实现了上右下左四个方向的三角形,在日常工作中,可以使用这个小技巧去实现一些三角形,如果没有做特殊的要求的话,那样就可以少麻烦UI设计师出图了。
进阶使用
以上是一些常规的使用,接下来说说这个技巧的进阶教程。在特定的需求中,可能会遇见这样一种情况,就是点击选项的时候,要求选项下面有一个类似对话框一样的,而且要跟随选项一起。这个时候可以把对话框分开,对话框的小三角形就可以写在选项上,然后利用伪类或者伪元素实现。
效果
Video_2024-08-14_213252
代码
<div class="btn active">选项一</div>
<div class="btn">选项二</div>
<div class="btn">选项三</div>
.btn {
width: 72px;
height: 32px;
text-align: center;
line-height: 32px;
border: 1px #ddd solid;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
margin-left: 16px;
}
.active {
color: tomato;
border-color: tomato;
position: relative;
}
/** 通过伪元素给按钮添加小三角形 */
.active::after {
content: '';
position: absolute;
bottom: -24px;
left: calc(50% - 16px);
width: 0;
height: 0;
border: 16px tomato solid;
border-radius: 4px;
border-top-color: transparent;
border-left-color: transparent;
border-right-color: transparent;
}
const btnDom = document.querySelectorAll('.btn');
btnDom.forEach(btn => {
//给按钮添加点击事件
btn.addEventListener('click', () => {
// 首先移除所有item的active类
btnDom.forEach(el => {
el.classList.remove('active');
});
// 然后给当前点击的元素添加active类
btn.classList.add('active');
})
});
以上是关于小三角形的基础用法和特殊需求的进阶用法,大家可以根据自身遇见的情况,实际需求出发,修改为适合自己项目的。