需求是这样,随着页面下拉到相应到位置,顶部导航相应到导航要高亮
比如 这个例子 链接
主要用到scrollTop 这个属性,
scrollTop: 设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离
jquery 可以这样获取
$(document.body).scrollTop()
看一下关键代码
var tab1Top=$(".tab1").offset().top, tab2Top=$(".tab2").offset().top, tab3Top=$(".tab3").offset().top;
$(window).on("scroll",function(){ var sTop = ($(document.body).scrollTop())+topMenuH; if(sTop < tab2Top){ //如果当前滚动到距离小于$(".tab2")距离文档顶部到距离 $(".topMenu ul li:nth-child(1)").addClass("active").siblings().removeClass("active"); return; } if(sTop >= tab2Top && sTop <= tab3Top){ $(".topMenu ul li:nth-child(2)").addClass("active").siblings().removeClass("active"); return; } if(sTop >= tab3Top){ $(".topMenu ul li:nth-child(3)").addClass("active").siblings().removeClass("active"); return; } })
哈哈哈