js如何实现导航栏跳转
使用锚点实现导航栏跳转
在HTML中设置锚点,通过<a>标签的href属性指向对应元素的id。
<!-- 导航栏 -->
<nav>
<a href="#section1">Section 1</a>
<a href="#section2">Section 2</a>
</nav>
<!-- 内容区 -->
<div id="section1">内容1</div>
<div id="section2">内容2</div>
使用JavaScript平滑滚动
通过scrollIntoView()方法实现平滑滚动效果。
document.querySelectorAll('nav a').forEach(anchor => {
anchor.addEventListener('click', function(e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
动态高亮当前章节
监听滚动事件,动态更新导航栏样式。
window.addEventListener('scroll', function() {
const sections = document.querySelectorAll('div[id]');
const scrollPosition = window.scrollY;
sections.forEach(section => {
const sectionTop = section.offsetTop;
const sectionHeight = section.clientHeight;
if (scrollPosition >= sectionTop - 50 && scrollPosition < sectionTop + sectionHeight - 50) {
const id = section.getAttribute('id');
document.querySelector(`nav a[href="#${id}"]`).classList.add('active');
} else {
const id = section.getAttribute('id');
document.querySelector(`nav a[href="#${id}"]`).classList.remove('active');
}
});
});
添加URL哈希历史
点击导航时更新浏览器地址栏。
document.querySelectorAll('nav a').forEach(anchor => {
anchor.addEventListener('click', function(e) {
window.location.hash = this.getAttribute('href');
});
});
响应式导航栏实现
使用CSS媒体查询和JavaScript结合实现移动端菜单。
const menuButton = document.querySelector('.menu-button');
const nav = document.querySelector('nav');
menuButton.addEventListener('click', function() {
nav.classList.toggle('active');
});
配套CSS示例:

@media (max-width: 768px) {
nav {
display: none;
}
nav.active {
display: flex;
flex-direction: column;
}
}






