javascript

当前位置:首页 > 前端 > javascript

导航栏滑动高亮效果

你这段 JS 是在做一个导航栏滑动高亮效果,常见于菜单 hover 时,下面有一条横条(highlight)跟着移动。
<ul class="bb3hd" id="nav">
  <li class="nav-item"><a href="/product/1/"><h2>滑触线系列</h2></a></li>
  <li class="nav-item"><a href="/product/2/"><h2>母线槽系列</h2></a></li>
  <li class="nav-item"><a href="/product/4/"><h2>电缆桥架系列</h2></a></li>
</ul>

<!-- 放在 ul 外面 -->
<div class="highlight" id="highlight"></div>

.bb3hd {
  position: relative;
}

.highlight {
  position: absolute;
  bottom: 0;
  height: 3px;
  background: #0056ff;
  transition: all .3s ease;
}



<script>
  /* =========================
     1️⃣ 获取导航相关元素
     nav:整个导航容器
     items:所有菜单项
     highlight:底部滑动高亮条
  ========================== */
  const nav = document.getElementById('nav');
  const items = nav.querySelectorAll('.nav-item');
  const highlight = document.getElementById('highlight');


  /* =========================
     2️⃣ 高亮条移动函数
     计算当前菜单项相对于 nav 的位置
     并修改高亮条的 left 和 width
  ========================== */
  function moveHighlightTo(item) {
    const navRect = nav.getBoundingClientRect();
    const itemRect = item.getBoundingClientRect();

    const left = itemRect.left - navRect.left;
    const width = itemRect.width;

    highlight.style.left = `${left}px`;
    highlight.style.width = `${width}px`;
  }


  /* =========================
     3️⃣ 鼠标移入事件
     - 移除所有 on 状态
     - 给当前菜单添加 on
     - 移动高亮条
  ========================== */
  items.forEach(item => {
    item.addEventListener('mouseenter', () => {
      items.forEach(i => i.classList.remove('on'));
      item.classList.add('on');
      moveHighlightTo(item);
    });
  });


  /* =========================
     4️⃣ 默认选中第一个菜单
     页面加载后初始化高亮条位置
  ========================== */
  const defaultItem = items[0];
  defaultItem.classList.add('on');

  window.addEventListener('load', () => {
    moveHighlightTo(defaultItem);
  });

</script>


上一篇:粒子动画 白色粒子

下一篇:已经是最后一篇

相关内容

文章评论

表情

共 0 条评论,查看全部
  • 这篇文章还没有收到评论,赶紧来抢沙发吧~