根据滚动条到达该位置对应的导航选项卡高亮

发布时间 2023-05-24 16:08:24作者: 阳菜

html

<nav> <ul> <li><a href="#section1">第一部分</a></li> <li><a href="#section2">第二部分</a></li> <li><a href="#section3">第三部分</a></li> <li><a href="#section4">第四部分</a></li> </ul> </nav> <section id="section1"> <h2>第一部分</h2> <p>这是第一部分的内容</p> </section> <section id="section2"> <h2>第二部分</h2> <p>这是第二部分的内容</p> </section> <section id="section3"> <h2>第三部分</h2> <p>这是第三部分的内容</p> </section> <section id="section4"> <h2>第四部分</h2> <p>这是第四部分的内容</p> </section>

 

css

nav {
position: fixed;
top: 0;
left: 0;
width: 100%;
background-color: #fff;
z-index: 999;
}

nav ul {
list-style: none;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
}

nav li {
margin: 0 10px;
}

nav a {
display: block;
padding: 10px;
text-decoration: none;
color: #333;
}

nav a.active {
color: #f00;
}

 

section {
height: 500px;
margin-top: 50px;
padding: 20px;
background-color: #eee;
}

js

$(document).ready(function() {
var nav_height = $('nav').outerHeight(); // 获取导航栏高度
var sections = $('section'); // 获取所有章节
var nav_links = $('nav a'); // 获取所有导航链接

$(window).scroll(function() {
var current_pos = $(this).scrollTop(); // 获取当前滚动条位置

sections.each(function() {
var top = $(this).offset().top - nav_height - 20; // 获取章节顶部位置
var bottom = top + $(this).outerHeight(); // 获取章节底部位置

if (current_pos >= top && current_pos <= bottom) {
nav_links.removeClass('active'); // 移除所有导航链接的 active 类
$('nav a[href="#' + $(this).attr('id') + '"]').addClass('active'); // 添加当前导航链接的 active 类
}
});
});
});