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 function getclsname(cls, parent) { var oparent = parent ? document.getElementById(parent) : document; var eles = []; var elements = oparent.getElementsByTagName("*"); for(var i = 0; i < elements.length; i++) { if(elements[i].className == cls) { eles.push(elements[i]); } } return eles; } 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 = getclsname("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 mu = menus[i]; var href = mu.href.split("#"); if(href[href.length - 1] != currentId) { removeClass(mu, "current"); } else { addClass(mu, "current"); } } } } }
非常感谢!
视屏里面的是这个,但是我一直运行不了,但改成了 var top = document.documentElement.scrollTop || document.body.scrollTop; 这样之后才行,为什么?
第35行改成var top = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;