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

如何制作可跳转到页面不同容器的导航栏?

实现页面内锚点导航栏(小型网站适用)

核心思路

用HTML锚点结合基础CSS/JS就能快速实现,不用复杂框架,完全适配小型网站需求。


1. HTML结构

先搭建导航栏和对应内容容器,导航链接通过#容器ID直接指向页面内的目标区域:

<!-- 导航栏 -->
<nav class="navbar">
  <a href="#home">首页</a>
  <a href="#about">关于我们</a>
  <a href="#services">服务</a>
  <a href="#contact">联系我们</a>
</nav>

<!-- 内容容器 -->
<div id="home" class="section">
  <h2>首页区域</h2>
  <p>这里是首页内容...</p>
</div>
<div id="about" class="section">
  <h2>关于我们</h2>
  <p>这里是关于我们的内容...</p>
</div>
<div id="services" class="section">
  <h2>服务区域</h2>
  <p>这里是服务介绍内容...</p>
</div>
<div id="contact" class="section">
  <h2>联系我们</h2>
  <p>这里是联系方式...</p>
</div>

2. CSS样式

给导航栏做基础美化,固定在顶部方便随时点击,同时给内容容器设置足够高度,确保能滚动到对应区域:

/* 导航栏样式 */
.navbar {
  position: fixed;
  top: 0;
  width: 100%;
  background-color: #333;
  padding: 1rem;
}
.navbar a {
  color: white;
  margin: 0 1rem;
  text-decoration: none;
}
.navbar a:hover {
  text-decoration: underline;
}

/* 内容容器样式 */
.section {
  padding: 2rem;
  margin-top: 60px; /* 避开固定导航栏的高度 */
  height: 80vh; /* 设置高度让页面能滚动 */
  border-bottom: 1px solid #eee;
}

3. 可选:平滑滚动效果

默认锚点跳转是瞬间定位,加几行JS实现平滑滚动,提升用户体验:

// 给所有导航链接添加平滑滚动
document.querySelectorAll('.navbar a').forEach(anchor => {
  anchor.addEventListener('click', function (e) {
    e.preventDefault();
    const targetId = this.getAttribute('href');
    document.querySelector(targetId).scrollIntoView({
      behavior: 'smooth'
    });
  });
});

注意事项

  • 确保每个内容容器的id和导航链接的href完全匹配(大小写敏感)
  • 如果导航栏固定顶部,记得给内容容器设置margin-top,避免内容被导航栏遮挡
  • 平滑滚动在现代浏览器都支持,无需额外兼容处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 16:22:03