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

移动端网站添加导航链接折叠按钮的技术咨询

解决方案

1. 修改HTML结构,添加汉堡按钮

在导航栏中加入汉堡按钮,并调整联系方式的结构以便样式控制:

<div id="navbar">
  <img src="../Assets/Banner3.png" alt="Banner" width="25%" height="60" id="logo">
  <button id="hamburger">☰</button>
  <div id="navbar-right">
    <a class="active" href="../index.html">Home</a>
    <a href="../htm/Contact.html">Contact</a>
    <a href="../htm/About.html">About</a>
    <a href="../htm/Social.html">Social</a>
    <a href="../htm/Website.html">Website</a>
    <a href="../htm/Computer.html">Computer</a>
    <a href="Phone">Phone</a>
  </div>
  <div class="navbar-contact">Contact us on | Email us</div>
</div>

2. 添加CSS样式,实现响应式布局

通过CSS设置导航栏基础布局、滚动效果和移动端适配逻辑:

/* 导航栏基础样式 */
#navbar {
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 80px 10px;
  transition: padding 0.3s ease;
  background: #fff; /* 替换为你的网站背景色 */
  box-sizing: border-box;
  z-index: 1000; /* 确保导航栏在页面最上层 */
}

#logo {
  transition: all 0.3s ease;
}

#navbar-right {
  display: flex;
  gap: 15px;
  align-items: center;
}

#navbar-right a {
  text-decoration: none;
  color: #333; /* 替换为你的链接文字颜色 */
}

/* 汉堡按钮默认隐藏 */
#hamburger {
  display: none;
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #333; /* 按钮颜色 */
}

.navbar-contact {
  margin-left: auto;
  margin-right: 20px;
}

/* 移动端响应式规则(屏幕宽度≤768px时生效) */
@media (max-width: 768px) {
  #navbar-right {
    position: absolute;
    top: 100%;
    left: 0;
    width: 100%;
    background: #fff;
    flex-direction: column;
    padding: 20px 0;
    display: none;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  }

  #hamburger {
    display: block;
  }

  /* 菜单展开状态 */
  #navbar-right.active {
    display: flex;
  }

  /* 移动端隐藏联系方式,可根据需求调整显示逻辑 */
  .navbar-contact {
    display: none;
  }
}

/* 滚动缩小后的导航栏样式 */
#navbar.scrolled {
  padding: 30px 10px;
}

#navbar.scrolled #logo {
  font-size: 25px;
}

3. 更新JavaScript逻辑,实现菜单展开/收起和滚动效果

修改原有滚动逻辑为类控制,并添加汉堡按钮的点击交互:

window.onscroll = function() {scrollFunction()};
document.getElementById('hamburger').addEventListener('click', toggleNav);

// 滚动伸缩逻辑
function scrollFunction() {
  const navbar = document.getElementById("navbar");
  if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {
    navbar.classList.add('scrolled');
  } else {
    navbar.classList.remove('scrolled');
  }
}

// 汉堡按钮切换菜单显示/隐藏
function toggleNav() {
  const navbarRight = document.getElementById('navbar-right');
  navbarRight.classList.toggle('active');
}

关键说明

  • 用CSS类(scrolled、active)控制状态,替代直接修改元素样式,提升代码可维护性
  • 移动端导航菜单默认隐藏,点击汉堡按钮切换显示状态,避免遮挡页面内容
  • 保留原有滚动伸缩效果,通过CSS过渡动画保证交互流畅性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 22:06:22