You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何制作示例图中第4款超简洁风格的navbar导航栏?

导航栏效果示例

第4款下划线跟随导航栏实现方案

实现原理

该款导航的核心效果是下划线跟随鼠标hover的导航项平滑移动,通过绝对定位的下划线元素,配合JS实时计算目标导航项的宽度与位置,加上CSS过渡动画即可实现。

完整代码实现

1. HTML 结构

<nav class="follow-navbar">
  <ul class="nav-wrapper">
    <li class="nav-tab active"><a>首页</a></li>
    <li class="nav-tab"><a>作品</a></li>
    <li class="nav-tab"><a>收藏</a></li>
    <li class="nav-tab"><a>关于</a></li>
    <!-- 跟随下划线元素 -->
    <span class="active-line"></span>
  </ul>
</nav>

2. CSS 样式

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.follow-navbar {
  width: 100%;
  max-width: 500px;
  margin: 30px auto;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.06);
}
.nav-wrapper {
  position: relative;
  display: flex;
  list-style: none;
}
.nav-tab {
  flex: 1;
  text-align: center;
  padding: 14px 0;
  cursor: pointer;
}
.nav-tab a {
  color: #666;
  text-decoration: none;
  font-size: 15px;
  font-weight: 500;
}
.nav-tab.active a {
  color: #2563eb;
}
/* 下划线核心样式 */
.active-line {
  position: absolute;
  bottom: 0;
  height: 2.5px;
  background: #2563eb;
  border-radius: 2px;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}

3. JavaScript 逻辑

const navWrapper = document.querySelector('.nav-wrapper')
const activeLine = document.querySelector('.active-line')
const allTabs = document.querySelectorAll('.nav-tab')

// 设置下划线位置的公共方法
function updateLinePosition(targetTab) {
  const tabWidth = targetTab.offsetWidth
  const tabLeftOffset = targetTab.offsetLeft
  activeLine.style.width = `${tabWidth}px`
  activeLine.style.left = `${tabLeftOffset}px`
}

// 初始化下划线默认在激活项位置
updateLinePosition(document.querySelector('.nav-tab.active'))

// 绑定hover事件
allTabs.forEach(tab => {
  // hover时移动到当前项
  tab.addEventListener('mouseenter', () => {
    updateLinePosition(tab)
  })
  // 鼠标离开导航后回到激活项位置
  tab.addEventListener('mouseleave', () => {
    updateLinePosition(document.querySelector('.nav-tab.active'))
  })
  // 点击切换激活状态
  tab.addEventListener('click', () => {
    allTabs.forEach(t => t.classList.remove('active'))
    tab.classList.add('active')
  })
})

如果不需要离开后回到激活项的效果,直接删除对应的mouseleave事件监听即可。如果只需要单个项hover显示下划线不需要跨项平滑移动,也可以直接用CSS伪元素实现,无需JS。

内容的提问来源于stack exchange,提问作者AirWalks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 22:27:00