导航 js 实现
实现导航功能的基本方法
使用JavaScript实现导航功能可以通过DOM操作和事件监听完成。以下是一个基础的实现方式:
// 获取导航元素
const navItems = document.querySelectorAll('.nav-item');
// 添加点击事件监听
navItems.forEach(item => {
item.addEventListener('click', function() {
// 移除所有active类
navItems.forEach(nav => nav.classList.remove('active'));
// 为当前点击项添加active类
this.classList.add('active');
});
});
平滑滚动到锚点
实现点击导航后平滑滚动到页面指定位置:
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function(e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
响应式导航菜单
创建移动设备友好的响应式导航:
const menuBtn = document.querySelector('.menu-btn');
const nav = document.querySelector('nav');
menuBtn.addEventListener('click', () => {
nav.classList.toggle('show');
});
CSS部分需要配合媒体查询和过渡效果:
nav {
transition: all 0.3s ease;
}
@media (max-width: 768px) {
nav {
position: fixed;
top: 0;
left: -100%;
width: 80%;
height: 100vh;
}
nav.show {
left: 0;
}
}
动态高亮当前浏览部分
根据滚动位置自动高亮导航项:
window.addEventListener('scroll', () => {
const sections = document.querySelectorAll('section');
const navLinks = document.querySelectorAll('.nav-link');
sections.forEach(sec => {
const top = window.scrollY;
const offset = sec.offsetTop - 150;
const height = sec.offsetHeight;
const id = sec.getAttribute('id');
if(top >= offset && top < offset + height) {
navLinks.forEach(link => {
link.classList.remove('active');
document.querySelector(`.nav-link[href="#${id}"]`).classList.add('active');
});
}
});
});
下拉菜单实现
为导航项添加下拉功能:
const dropdowns = document.querySelectorAll('.dropdown');
dropdowns.forEach(dropdown => {
const btn = dropdown.querySelector('.dropdown-btn');
const menu = dropdown.querySelector('.dropdown-menu');
btn.addEventListener('click', () => {
menu.classList.toggle('show');
});
// 点击外部关闭下拉菜单
document.addEventListener('click', (e) => {
if(!dropdown.contains(e.target)) {
menu.classList.remove('show');
}
});
});
导航栏固定定位
实现滚动时固定导航栏:

const navbar = document.querySelector('.navbar');
let lastScroll = 0;
window.addEventListener('scroll', () => {
const currentScroll = window.pageYOffset;
if(currentScroll <= 0) {
navbar.classList.remove('scroll-up');
}
if(currentScroll > lastScroll && !navbar.classList.contains('scroll-down')) {
navbar.classList.remove('scroll-up');
navbar.classList.add('scroll-down');
}
if(currentScroll < lastScroll && navbar.classList.contains('scroll-down')) {
navbar.classList.remove('scroll-down');
navbar.classList.add('scroll-up');
}
lastScroll = currentScroll;
});
这些方法可以根据具体项目需求组合使用或单独实现。实际应用中需要考虑浏览器兼容性、性能优化和可访问性等因素。






