我总是感觉这样写也是对的,为什么不对呢,哪位大神给我讲讲为什么?
//定义getByClassName函数,让函数实现根据class name获取对象并返回
function getByClassName(obj,cls){
var elements = obj.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 )){
//remove
var reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
obj.className = obj.className.replace(reg, "");
}
}
//定义getByClassName函数,让函数实现给对象增加class
function addClassName( obj, cls ){
if(!hasClass(obj,cls)){
obj.className += " "+cls;
}
}
window.onload = function(){
window.onscroll = function(){
var top = 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;
}
}
//请补充此处代码,给正确的menu下的a元素class赋值current
if(currentId){
var _Link=getByClassName(document.getElementById("menu"),"current");
var _href=_Link.getAttribute("href");
var _menu=document.getElementById("menu");
if(_href!="#"+currentId){
removeClass(_menu,"current");
//_menu.className("");
}else{
addClassName(_menu,"current");
// _menu.className("current");
}
}
}
}