javascript 滑动导航效果

HTML布局

  • 头条
  • 行情
  • 政策
  • 股市
  • 热点

CSS

* {
      margin: 0;
      padding: 0;
    }

    li {
      list-style-type: none;
    }

    .news-title {
      position: relative;
      border-bottom: 0.2rem solid #e5e8f0;
      width: 100%;
    }

    .news-module {
      display: flex;
    }

    .news-module>li {
      width: 20%;
      text-align: center;
      font-size: 1.3rem;
      line-height: 3.5rem;
      color: #000;
      background-color: #FFFFFF;
      cursor: pointer;
    }

    .news-module .active {
      color: #259251;
      font-size: 1.35rem;
    }

    .news-slider {
      background-color: #38AD67;
      height: 0.35rem;
      width: 2.5rem;
      transition: 0.5s;
      position: absolute;
      bottom: -0.2rem;
      left: 0.5rem;
      border-radius: 0.3rem;
    }

js

 document.querySelector(".news-module").addEventListener("click", function (e) {
      let active = document.querySelector(".news-module>li.active")
      active.classList.remove("active")
      e.target.classList.add("active")
      reckon({value:e.target})
    })

    function reckon({value = document.querySelector('.news-module>li.active')} = {}) {
      let th_width = value.clientWidth;// 获取带有active标识的li
      let th_left = value.offsetLeft// 获取带有active的li到左边偏移多少px
      let slider_width = document.querySelector(".news-slider").clientWidth;// 滑块宽度
      let slider_left = th_left + (th_width / 2) - (slider_width / 2)// 设置滑块偏移默认位置 
      document.querySelector(".news-slider").style.left = `${slider_left}px`// 改变滑块位置
    }
    reckon()

效果

你可能感兴趣的:(javascript)