点击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");
}
});