js方法
<script>
//定义getByClassName函数,让函数实现根据class name获取对象并返回
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 )){
//remove
obj.className += " "+ cls;
}
}
//定义getByClassName函数,让函数实现给对象增加class
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 getScrollTop() {
var scrollPos;
if (window.pageYOffset) {
scrollPos = window.pageYOffset; }
else if (document.compatMode && document.compatMode != 'BackCompat')
{ scrollPos = document.documentElement.scrollTop; }
else if (document.body) { scrollPos = document.body.scrollTop; }
return scrollPos;
}
window.onload = function(){
window.onscroll = function(){
// 获取滚动条滚动距离
// var top = document.documentElement ? document.documentElement.scrollTop : document.body.scrollTop;
var top=getScrollTop()
// console.log(top)
var menus = document.getElementById("menu").getElementsByTagName("a");
// var items = document.getElementById("content").getElementByClassName("item")
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;
console.log(_itemTop)
if( top > _itemTop - 200 ){
// 没有像jq一样加#,因为判定不需要
currentId = _item.id;
} else {
break;
}
}
//请补充此处代码,给正确的menu下的a元素class赋值current
if(currentId){
for( var j = 0 ; j < menus.length ; j++){
var _menu = menus[j];
var _href = _menu.href.split("#");
//一个个找,如果是这个id就高亮,不是就不要高亮
if (_href[_href.length - 1] != currentId) {
removeClass(_menu,"current");
}else{
addClass(_menu,"current");
}
}
}
}
}
</script>
网友评论