<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 )){
//remove
var reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
obj.className = obj.className.replace(reg, "");
}
}
//定义getByClassName函数,让函数实现给对象增加class
function addClass(obj, cls){
if(!hasClass(obj, cls)){
obj.className += " " + cls;
}
}
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]);
};
};
}
window.onload = function(){
window.onscroll = function(){
var top = document.documentElement ? document.documentElement.scrollTop : document.body.scrollTop;
/*兼容IE浏览器*/
var menu = document.getElementById('menu').document.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 = _itemTop;
}else{
break;
}
}
if (currentId) {
for(var j = 0 ; j < menu.length ; j++){
var _menu = menu[j];
var _href = _menu.herf.split("#");
if (_href[_href.length - 1] != currentId) {
removeClass(_menu,"current");
}else{
addClass(_menu,"current");
};
}
};
}
}
</script>