<script type="text/javascript"> 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 = " current"; } // obj.className = " current"; } //根据CLASSname获取元素 // function getByClassName( obj, cls ){ // var elenemts = obj.getElementsByTageName("*"); // alert(elements); // var result = []; // for(var i = 0 ; i < elenemts.length; i++){ // if(elenemts[i].className == cls){ // result.push(elements[i]); // } // } // return result; // } window.onload = function() { window.onscroll = function(){ var top = document.body.scrollTop || document.documentElement.scrollTop; var menus = document.getElementById("menu").getElementsByTagName("a"); var items = document.getElementById("content").getElementsByClassName("item"); var currentId = ""; for ( var i=0; i< items.length; i++ ){ var _item = items[i]; var _itemTop = _item.offsetTop; // console.log(top); // console.log(_itemTop-200); if( top > _itemTop - 200){ currentId = _item.id; // alert(currentId); } else { break; } } if(currentId){ //给正确A元素加CLASS for(var i = 0; i < menus.length; i++){ var _menu = menus[i]; var _href = _menu.href.split("#"); // console.log(_href); if(_href[_href.length-1] == currentId){ addClass(_menu,"current"); } else{ removeClass(_menu,"current"); // alert(_menu.className); } } } } } </script>
如果你是在做练习题,还要检查把html里面的menu下面a的href="#"对应锚点补充上去,
给最佳啊,积分也不知道拿来干嘛的
getByClassName()这个函数被注释掉了,取消注释然后var items = document.getElementById("content").getElementsByClassName("item");替换为
var items = getByClassName(document.getElementById("content"), "item");