监听导航点击,滚动到相应位置

这篇博客介绍了一种使用jQuery实现页面点击导航链接时平滑滚动到对应内容区域的方法,并在滚动过程中动态高亮当前可视区域的导航项。通过获取元素距离顶部的位置,监听点击和滚动事件,实现了流畅的滚动效果和导航指示。
摘要由CSDN通过智能技术生成

点击id=“nav”,页面滚动到class=“content”

$(document).on('click', '#nav', function () {
	$('html, body').animate({
		scrollTop:$('.content').offset().top,
	},1000)
});

1.获取页面各元素距离顶部距离,-100是减去导航条的高度

var htmlTop = 0;
var goodsTop = $('.content1').offset().top-100;
var aboutTop = $('.content2').offset().top-100;
var businessTop = $('.content3').offset().top-100;
var openTop = $('.content4').offset().top-100;

2.监听导航点击,滚动到相应位置

$('#nav .item').click(function(){
	let index = $(this).index();
	if(index == 0){
		$('html, body').animate({scrollTop:0},500)
	}else if(index == 1){
		$('html, body').animate({scrollTop:goodsTop},500)
	}else if(index == 2){
		$('html, body').animate({scrollTop:aboutTop},500)
	}else if(index == 3){
		$('html, body').animate({scrollTop:businessTop},500)
	}else if(index == 4){
		$('html, body').animate({scrollTop:openTop},500)
	}
})

3.滚多过后,对导航进行高亮显示

$(window).scroll(function(e){
	htmlTop = $(window).scrollTop();
	if(htmlTop == 0){
		$(".nav .item").eq(0).addClass("active").siblings().removeClass("active");
	}else if(htmlTop >= goodsTop && htmlTop < aboutTop){
		$(".nav .item").eq(1).addClass("active").siblings().removeClass("active");
	}else if(htmlTop >= aboutTop && htmlTop < businessTop){
		$(".nav .item").eq(2).addClass("active").siblings().removeClass("active");
	}else if(htmlTop >= businessTop && htmlTop < openTop){
		$(".nav .item").eq(3).addClass("active").siblings().removeClass("active");
	}else if(htmlTop >= openTop){
		$(".nav .item").eq(4).addClass("active").siblings().removeClass("active");
	}
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值