选项卡边框项重叠解决方案

760 阅读1分钟

概述

选项卡这个功能在日常开发中再常见不过了,当我们使用工程化项目的时候,一般组件库都提供了现成的组件,很少自己去写,这里记录当我们需要自己实现选项卡的时候的一个注意事项,也就是边框重叠问题。

基本结构

css

  <style>
      ul {
        list-style: none;
        display: flex;
        width: 500px;
      }
      li {
        border: 1px solid #ccc;
        padding: 10px 15px;
        transition: all 0.25s linear;
      }
      li:hover {
        color: #008c8c;
        border-color: #008c8c;
        cursor: pointer;
      }
      .active {
        color: #008c8c;
        border-color: #008c8c;
      }
    </style>

html

  <body>
    <ul>
      <li class="item active">首页</li>
      <li class="item">详情</li>
      <li class="item">我的</li>
      <li class="item">关于</li>
    </ul>
  </body>

js


  <script>
    let ulWrap = document.querySelector('ul');
    let frontActive = ulWrap.firstElementChild;
    ulWrap.addEventListener('click', e => {
      const target = e.target,
        targetClassList = [...target.classList];
      if (targetClassList.includes('item')) {
        if (targetClassList.includes('active')) return;
        console.log(target.textContent);
        frontActive && frontActive.classList.remove('active');
        target.classList.add('active');
        frontActive = target;
      }
    });
  </script>

效果:

动画.gif

问题1

可以看到使用最朴素的方式实现起来还是很方便的,但是有个缺点就是中间的li的两遍多出了1px的边框,视觉效果很明显有问题,最简单的方式就是使用margin负值。

   li {
        border: 1px solid #ccc;
        padding: 10px 15px;
        transition: all 0.25s linear;
        //加上这个
         margin-right: -1px; 
      }

效果:

动画.gif

问题2:

上面边框多出的1px问题解决了,但是又出现了一个新的问题就是,我们点击的时候,高亮的时候,右边的边框不见了。原因就是margin负值塌陷的时候,我们的层级跑下面去了,只需要加上定位就可以了,用来提升层级关系。

     li:hover {
        color: #008c8c;
        border-color: #008c8c;
        //新加
        position: relative;
        cursor: pointer;
      }
      .active {
        color: #008c8c;
        border-color: #008c8c;
        //新加
        position: relative;
      }

最终效果

动画.gif