效果图如下: 适用导航栏距离顶部还有一个div的高度
<script>//获取导航栏(.nav)到顶部(.header)距离var ntop =$(".nav").offset().top;//获取导航栏高度var nheight =$(".nav").outerHeight();//监听向下滑动了多少var scrollheight = 0;$(window).scroll(function (){scrollheight = $(this).scrollTop();//判断是否需要固定导航栏if(scrollheight >= ntop){//改变导航栏的position$(".nav").css({"position":"fixed","top":"0"});//改变内容的上外边距(.content)$(".content").css({"margin":nheigth});}else{$(".nav").css({"position":"static"});$(".content").css({"margin":"0"});}});</script>