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

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 类
}
});
});
});

 

    <!-- if ($('.solve_nav').length > 0) {
    var thisclass = $('.solve_list');
    var thispar = $('.solve_nav');
    addEvent(window, 'scroll', function () {
    var category = thispar.offset().top;
    var xflmnavjs2 = $(window).scrollTop();
    if (xflmnavjs2 > category) {
    thisclass.addClass('active');
    }
    else {
    thisclass.removeClass('active');
    }
    });
    .solve_list.active {
    position: fixed;
    z-index: 66;
    background: #fff;
    top: 100px;
    display: flex;
    justify-content: center;
    width: 100%;
    }
    } -->
posted @   阳菜  阅读(123)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示