<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>地狗购物网——网页定位导航效果</title> <style> * { margin: 0; padding: 0; } body { font-size: 12px; line-height: 1.7; } li { list-style: none; } #content { width: 800px; margin: 0 auto; padding: 20px; } #content h1 { color: #0088bb; } #content .item { padding: 20px; margin-bottom: 20px; border: 1px dotted #0088bb; } #content .item h2 { font-size: 16px; font-weight: bold; border-bottom: 2px solid #0088bb; margin-bottom: 10px; } #content .item li { display: inline; margin-right: 10px; } #content .item li a img { width: 230px; height: 230px; border: none; } #menu { position: fixed; top: 100px; left: 50%; margin-left: 400px; width: 80px; } #menu ul li a { display: block; margin: 5px 0; font-size: 14px; font-weight: bold; color: #333; width: 80px; height: 50px; line-height: 50px; text-decoration: none; text-align: center; } #menu ul li a:hover, #menu ul li a.current { color: #fff; background: #0088bb; } /*ie6 hack*/ * html, * html body { background-image: url(about:blank); background-attachment: fixed; } * html #menu { /*position: fixed;*/ position: absolute; top: expression(((e=document.documentElement.scrollTop)?e:document.body.scrollTop)+100+'px'); } </style> <script> //注意掌握正则表达式 function hasClass( obj, cls ){ return obj.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)")); } function removeClass( obj, cls ){ if( hasClass( obj, cls )){ //remove var reg = new RegExp("(\\s|^)" + cls + "(\\s|$)"); obj.className = obj.className.replace(reg, ""); } } function addClass(obj,cls){ if(!hasClass(obj,cls)){ obj.className +=" "+cls; } } //定义getByClassName函数,让函数实现给对象增加class //注意传入参数对象、函数内部for循环的使用以及if判断语句中的条件的书写 function getByClassName(obj,cls){ var elements=obj.getElementsByTagName("*"); var result=[]; for(var j=0;j<elements.length;j++){ if(elements[j].className==cls){ result.push(elements[j]); } } return result; } //主要js window.onload=function(){ window.onscroll=function(){ var top=document.documentElement?document.documentElement.scrollTop:document.body.scrollTop; var menus = document.getElementById("menu").getElementsByTagName("a"); var items=getByClassName(document.getElementById("content"),"item"); var currentId=""; for(var i=0;i<items.length;i++){ var item=items[i]; var itemTop=item.offsetTop; if(top>itemTop-200){ currentId=item.id; }else{ break; } } if(currentId){ for(var i=0;i<menus.length;i++){ var menu=menus[i]; var href=menu.href.split("#"); if(href[href.length-1]!=currentId){ removeClass(menu,"current"); }else{ addClass(menu,"current"); } } } } } //请补充此处代码,给正确的menu下的a元素class赋值current </script> </head> </html>
教程里的有问题,不如改成var top = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
前后换一下位置就没问题了
改为var top=document.documentElement.scrollTop||document.body.scrollTop
给下html结构看一下