js实现导航菜单
使用HTML和CSS创建基础结构
导航菜单的基础结构通常由HTML的无序列表(<ul>)和列表项(<li>)组成,每个列表项包含一个链接(<a>)。CSS用于样式化菜单,使其水平或垂直排列。
<nav class="navbar">
<ul class="nav-list">
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
.navbar {
background-color: #333;
padding: 10px 0;
}
.nav-list {
list-style-type: none;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
}
.nav-list li {
margin: 0 15px;
}
.nav-list a {
color: white;
text-decoration: none;
font-size: 18px;
}
.nav-list a:hover {
color: #4CAF50;
}
添加响应式设计
使用媒体查询使导航菜单在移动设备上折叠为一个汉堡菜单。通过JavaScript切换菜单的显示和隐藏。

@media (max-width: 768px) {
.nav-list {
flex-direction: column;
display: none;
}
.nav-list.active {
display: flex;
}
.hamburger {
display: block;
cursor: pointer;
padding: 10px;
}
}
实现汉堡菜单功能
JavaScript用于监听汉堡菜单的点击事件,切换导航菜单的显示状态。
document.addEventListener('DOMContentLoaded', function() {
const hamburger = document.querySelector('.hamburger');
const navList = document.querySelector('.nav-list');
hamburger.addEventListener('click', function() {
navList.classList.toggle('active');
});
});
添加平滑滚动效果
为导航菜单中的链接添加平滑滚动功能,提升用户体验。

document.querySelectorAll('.nav-list a').forEach(anchor => {
anchor.addEventListener('click', function(e) {
e.preventDefault();
const targetId = this.getAttribute('href');
const targetElement = document.querySelector(targetId);
targetElement.scrollIntoView({
behavior: 'smooth'
});
});
});
高亮当前活动菜单项
根据用户滚动位置,动态高亮显示当前所在的菜单项。
window.addEventListener('scroll', function() {
const sections = document.querySelectorAll('section');
const navLinks = document.querySelectorAll('.nav-list a');
sections.forEach(section => {
const sectionTop = section.offsetTop;
const sectionHeight = section.clientHeight;
if (window.scrollY >= sectionTop - 50 && window.scrollY < sectionTop + sectionHeight - 50) {
const id = section.getAttribute('id');
navLinks.forEach(link => {
link.classList.remove('active');
if (link.getAttribute('href') === `#${id}`) {
link.classList.add('active');
}
});
}
});
});
添加下拉子菜单功能
对于有子菜单的导航项,实现鼠标悬停或点击展开子菜单的功能。
<li class="dropdown">
<a href="#">Dropdown</a>
<ul class="dropdown-menu">
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
</ul>
</li>
.dropdown {
position: relative;
}
.dropdown-menu {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}
.dropdown:hover .dropdown-menu {
display: block;
}
document.querySelectorAll('.dropdown').forEach(item => {
item.addEventListener('click', function() {
this.querySelector('.dropdown-menu').classList.toggle('show');
});
});






