导航html如下
<div class="main_nav"> <a class="nav_01 active_01" href="javascript:;"></a> <a class="nav_02" href="javascript:;"></a> <a class="nav_03" href="javascript:;"></a> <a class="nav_04" href="javascript:;"></a> </div>
导航css如下
<style> .main_nav{ width:50px; height:260px; position:fixed; bottom:90px; left:200px;} .main_nav a{ display:block; width:70px; height:70px; background:#dedede; margin-top:1px; text-align:center; line-height:50px; font-size:18px; background:url(img/nav_bg.png) no-repeat; } .main_nav .nav_01{ background-position:0px 0px;} .main_nav .nav_02{ background-position:0px -71px;} .main_nav .nav_03{ background-position:0px -143px;} .main_nav .nav_04{ background-position:0px -215px;} .main_nav .active{ background-position-x:-75px;} .main_nav .active_01{ background-position:-75px 0px;} .main_nav .active_02{ background-position:-75px -71px;} .main_nav .active_03{ background-position:-75px -143px;} .main_nav .active_04{ background-position:-75px -215px;} </style>
js代码如下
$(function(){ $(window).scroll(function() { var scrollHight=$(window).scrollTop(); var mainHight01=$(".main_01").offset().top; var mainHight02=$(".main_02").offset().top; var mainHight03=$(".main_03").offset().top; var mainHight04=$(".main_04").offset().top; if(scrollHight<mainHight02){ $(".nav_01").addClass("active_01"); $(".nav_02").removeClass("active_02"); $(".nav_03").removeClass("active_03"); $(".nav_04").removeClass("active_04"); } if(scrollHight>mainHight02&&scrollHight<mainHight03){ $(".nav_01").removeClass("active_01"); $(".nav_02").addClass("active_02"); $(".nav_03").removeClass("active_03"); $(".nav_04").removeClass("active_04"); } if(scrollHight>mainHight03&&scrollHight<mainHight04){ $(".nav_03").addClass("active_03"); $(".nav_02").removeClass("active_02"); $(".nav_01").removeClass("active_01"); $(".nav_04").removeClass("active_04"); } if(scrollHight>mainHight04){ $(".nav_04").addClass("active_04"); $(".nav_02").removeClass("active_02"); $(".nav_03").removeClass("active_03"); $(".nav_01").removeClass("active_01"); } }); $(".main_nav a").each(function(index, element) { $(this).click(function(){ $("html,body").animate({scrollTop:$(".main_0"+(index+1)).offset().top+20},10); }); }); });
这里需要说明的是$("html,body").animate({scrollTop:$(".main_0"+(index+1)).offset().top+20},10)这段话里的“.main_0”,这个是在你的页面中需要切换导航锚点的div中需要添加的类名,需要按此格式依次添加如main_01、main_02、main_03
$(".main_0"+(index+1)).offset().top+20中的+20是根据页面实际情况调节的值,主要是为了避免滚动事件和鼠标点击事件保持一致!
![](https://images2015.cnblogs.com/blog/662449/201510/662449-20151021141944630-616339854.png)