手撸原生html5 过渡型tabbar

137 阅读1分钟
  1. 在html中构建基本结构 内容如下
...其他代码
<body>
    <div class="container">
     <div id='tabBox'>
      <div class="item">tab1</div>
      <div class="item">tab22</div>
      <div class="item">tab333</div>
      <div class="item">tab4444</div>
     </div>
    </div>
</body>
...其他代码
  1. 构建基本样式
<style>
    *{margin: 0;padding: 0;}
    :root{--width:0;--left:0;} //使用了css3 的css变量
    html,body{width: 100vw;height: 100vh;}
    .container{
      background: #e0eaf7;
      overflow: hidden;
      height: 100%;
    }
    .container #tabBox{
      margin: 0 auto;
      display: flex;
      width: 70vw;
      justify-content: space-around;
      margin-top: 150px;
      border-radius: 24px;
      position: relative;
      border: 4px solid #fff;
    }
    .container #tabBox .item{
      margin: 0;
      padding: 10px 20px;
      z-index: 10;
      cursor: pointer;
    }
    .active{color:#fff}
    #tabBox::before{
      content: '';
      height: 100%;
      width: var(--width);
      left: var(--left);
      position: absolute;
      background: #598bf0;
      border-radius: 24px;
      transition: all 0.4s ease-in-out;
    }
</style>
  1. 在JS中实现点击切换
<script>
    window.onload = function(){
      var oParentDiv = document.getElementById('tabBox'); //获取父元素
      var oChildDiv = oParentDiv.getElementsByTagName('div'); //获取子元素
      var root = document.querySelector(':root');
      function setCssVar(dom){ //设置active样式 和 css变量
        const {left,width} = dom.getBoundingClientRect() //获取子元素距离屏幕左边的距离和宽度,为了后面赋值给css变量
        const {left:parentLeft} = oParentDiv.getBoundingClientRect() //这里是es6结构并重命名
        dom.className = 'item active'
        //设置:root中的css变量
        root.style.setProperty('--width',width+'px') 
        root.style.setProperty('--left',left-parentLeft-5+'px') //这里的值可以自己调节
      }
      setCssVar(oChildDiv[0]) // 初始化 默认样式
      for(let i = 0; i < oChildDiv.length;i++){ //给每一个子元素div添加点击事件
        oChildDiv[i].onclick = function(){
          for(let j = 0 ; j < oChildDiv.length; j++){ //先清除其他样式
            oChildDiv[j].className = 'item'
          }
          setCssVar(this) 
        }
      }
    }
  </script>
有能继续优化点还望评论提点一下,谢谢~