js实现导航菜单
实现导航菜单的基本结构
使用HTML和CSS创建导航菜单的基础结构,通常采用无序列表<ul>实现。HTML结构示例:
<nav class="navbar">
<ul>
<li><a href="#home">首页</a></li>
<li><a href="#services">服务</a></li>
<li><a href="#about">关于</a></li>
<li><a href="#contact">联系</a></li>
</ul>
</nav>
基础CSS样式示例:
.navbar ul {
list-style-type: none;
margin: 0;
padding: 0;
display: flex;
gap: 20px;
}
.navbar a {
text-decoration: none;
color: #333;
padding: 10px 15px;
}
添加交互效果
通过JavaScript实现鼠标悬停效果和点击事件。以下代码为菜单项添加悬停高亮和点击激活状态:
const navItems = document.querySelectorAll('.navbar li');
navItems.forEach(item => {
// 鼠标悬停效果
item.addEventListener('mouseenter', () => {
item.style.backgroundColor = '#f0f0f0';
});
item.addEventListener('mouseleave', () => {
item.style.backgroundColor = '';
});
// 点击激活状态
item.addEventListener('click', () => {
navItems.forEach(i => i.classList.remove('active'));
item.classList.add('active');
});
});
对应的CSS激活状态样式:
.navbar li.active {
border-bottom: 2px solid #0066cc;
}
实现响应式导航
针对移动设备添加汉堡菜单功能。修改HTML结构:
<nav class="navbar">
<button class="menu-toggle">☰</button>
<ul class="nav-list">
<!-- 菜单项保持不变 -->
</ul>
</nav>
添加响应式CSS:
.menu-toggle {
display: none;
background: none;
border: none;
font-size: 24px;
}
@media (max-width: 768px) {
.menu-toggle {
display: block;
}
.nav-list {
display: none;
flex-direction: column;
}
.nav-list.show {
display: flex;
}
}
JavaScript控制菜单显示/隐藏:
const menuToggle = document.querySelector('.menu-toggle');
const navList = document.querySelector('.nav-list');
menuToggle.addEventListener('click', () => {
navList.classList.toggle('show');
});
添加滚动效果
实现页面滚动时导航栏固定定位和样式变化:
window.addEventListener('scroll', () => {
const navbar = document.querySelector('.navbar');
if (window.scrollY > 50) {
navbar.style.position = 'fixed';
navbar.style.top = '0';
navbar.style.width = '100%';
navbar.style.background = 'white';
navbar.style.boxShadow = '0 2px 5px rgba(0,0,0,0.1)';
} else {
navbar.style.position = 'relative';
navbar.style.background = '';
navbar.style.boxShadow = '';
}
});
高亮当前可见区域
根据滚动位置自动高亮对应的导航项:

const sections = document.querySelectorAll('section');
window.addEventListener('scroll', () => {
let current = '';
sections.forEach(section => {
const sectionTop = section.offsetTop;
const sectionHeight = section.clientHeight;
if (pageYOffset >= (sectionTop - sectionHeight / 3)) {
current = section.getAttribute('id');
}
});
navItems.forEach(item => {
item.classList.remove('active');
if (item.querySelector('a').getAttribute('href') === `#${current}`) {
item.classList.add('active');
}
});
});






