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

效果(图片失效查看,可以点击预览)

image


hhemin
23 声望1 粉丝

无bug是梦想,年薪百万是理想