前端实用小技巧之巧用小三角形

前端实用小技巧

今天分享一个前端常用的实用小技巧,在我们前端的开发过程中,经常会遇见一些 “三角形”,其实这些“三角形”完全可以不用找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');
  })
});

以上是关于小三角形的基础用法和特殊需求的进阶用法,大家可以根据自身遇见的情况,实际需求出发,修改为适合自己项目的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值