<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>联动菜单</title> <style type="text/css"> *{ margin:0; padding:0;} li{ list-style:none;} .nav-wrapper{ width:100%; position:fixed; top:0;} .nav{ width:1200px; height:30px; line-height:30px; margin:0 auto;} .nav li{ float:left; width:100px; text-align:center; background:#F2F2F2; margin-right:5px;} .nav li.current{ color:#fff; background:red;} .box{ width:1200px; height:200px; background:#CCC; margin:10px auto 0;} </style> <script type="text/javascript"> window.onload=function(){ var lis=document.getElementById('nav').getElementsByTagName('li'); var divs=document.getElementById('boxWrapper').getElementsByTagName('div'); var i=0; window.onscroll=function(){ var scrollTop=document.documentElement.scrollTop||document.body.scrollTop; var offsetHeight=document.documentElement.offsetHeight||document.body.offsetHeight; linkageMenu(divs,lis,120,'current',scrollTop,offsetHeight) }; }; function linkageMenu(element,nav,value,className,scrollTop,offsetHeight){ var i=0; var index=0; if(scrollTop>offsetHeight/2){ for(i=element.length-1; i>=0; i--){ if(element[i].getBoundingClientRect().top<value){ index=i; console.log(index); break; } } }else{ for(i=0; i<element.length; i++){ if(element[i].getBoundingClientRect().top<value){ index=i; } } } for(i=0; i<nav.length; i++){ nav[i].className=''; } nav[index].className=className; } </script> </head> <body style="height:2800px;"> <div class="nav-wrapper"> <div class="nav" id="nav"> <ul> <li>菜单一</li> <li>菜单二</li> <li>菜单三</li> <li>菜单四</li> <li>菜单五</li> <li>菜单六</li> <li>菜单七</li> <li>菜单八</li> <li>菜单九</li> <li>菜单十</li> <li>菜单十一</li> </ul> </div> </div> <br /><br /> <div id="boxWrapper"> <div class="box"> <h1>菜单一</h1> </div> <div class="box"> <h1>菜单二</h1> </div> <div class="box"> <h1>菜单三</h1> </div> <div class="box"> <h1>菜单四</h1> </div> <div class="box"> <h1>菜单五</h1> </div> <div class="box"> <h1>菜单六</h1> </div> <div class="box"> <h1>菜单七</h1> </div> <div class="box"> <h1>菜单八</h1> </div> <div class="box"> <h1>菜单九</h1> </div> <div class="box"> <h1>菜单十</h1> </div> <div class="box"> <h1>菜单十一</h1> </div> </div> </body> </html>