乐趣区

关于javascript:javascript-滑动导航效果

HTML 布局

<div class="news-title">
    <ul class="news-module" id="news-module">
      <li> 头条 </li>
      <li class="active"> 行情 </li>
      <li> 政策 </li>
      <li> 股市 </li>
      <li> 热点 </li>
    </ul>
    <!-- 滑动条 -->
    <div class="news-slider"></div>
  </div>

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()

成果

退出移动版