function getByClassName(obj,cls){
var elements=document.getElementsByTagName('*');
var result=[];
for(var i=0;i<elements.length;i++){
if(elements[i].className==cls){
result.push(elements[i]);
}
}
return result;
}
function hasClass(obj,cls){
return obj.className.match(new RegExp("(\\s|^)"+cls+"(\\s|$)"));
}
function removeClass(obj,cls){
if(hasClass(obj,cls)){
var reg=new RegExp("(\\s|^)"+cls+"(\\s|$)");
obj.className=obj.className.replace(reg,'');
}
}
function addClass(obj,cls){
if(!hasClass(obj,cls)){
obj.className+=' '+cls;
}
}
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 oitem=items[i];
var oitemTop=oitem.offsetTop;
console.log(oitem.offsetTop);
if(top>oitemTop-200){
currentId=oitem.id;
}else{
break;
}
}
if(currentId){
for(var j=0;j<menus.length;j++){
var omenu=menus[j];
var ohref=omenu.href.split('#');
if(ohref[ohref.length-1]!=currentId){
removeClass(omenu,'current');
}else{
addClass(omenu,'current');
}
}
}
}
}
1,getByClassName 里面的 var elements=document.getElementsByTagName('*');应该为var elements=obj.getElementsByTagName('*');
2,var top=document.documentElement?document.documentElement.scrollTop:document.body.scrollTop;改成var top=document.documentElement.scrollTop||document.body.scrollTop;