导航滚动高亮js代码

这段代码用于在用户滚动页面时,根据当前滚动位置高亮相应的导航链接。它的作用是判断当前页面的滚动位置是否在某个 section 的范围内,如果在这个范围内,就为对应的导航链接添加 active 类,从而实现导航链接的高亮。
html代码如下:

		<div class="nav">
			<a href="#section1">section1</a>
			<a href="#section2">section2</a>
			<a href="#section3">section3</a>
		</div>
		<div id="section1" class="section">
			section1xxxxxxxxxxxxxxxxxx
		</div>
		<div id="section2" class="section">
			section2xxxxxxxxxxxxxxxxxx
		</div>
		<div id="section3" class="section">
			section3xxxxxxxxxxxxxxxxxx
		</div>

css代码如下:

<style>
			.nav {
				width: 80%;
				margin: auto;
				display: flex;
				column-gap: 20px;
				justify-content: center;
				position: sticky;
				top: 0;
			}

			.nav a {
				color: black;
			}

			.nav a.active {
				color: aquamarine;
			}

			.section {
				height: 800px;
				width: 80%;
				margin: auto;
				border: 1px solid #eee;
				margin-top: 20px;
			}
		</style>

js代码如下:

		<script type="text/javascript">
			window.addEventListener('DOMContentLoaded', () => {
				const navLink = document.querySelectorAll('.nav a');
				const sections = document.querySelectorAll('.section');
				function updateNav(currentPosition) {
					navLink.forEach(link => {
						link.classList.remove('active');
						const section = document.querySelector(link.hash);
						if (section.offsetTop <= currentPosition && section.offsetTop + section.offsetHeight >
							currentPosition) {
							link.classList.add('active');
						}
					})
				}
				
				window.addEventListener('scroll', () => {
					let currentPosition = window.scrollY || document.documentElement.scrollTop;
					updateNav(currentPosition);
				})
				
				navLink.forEach(link => {
					link.addEventListener('click', e => {
						e.preventDefault();
						const section = document.querySelector(link.hash);
						section.scrollIntoView({
							behavior: 'smooth'
						});
					})
				})
			})
		</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值