javascript练习:导航随内容滚动而跟随变化

window.onload=function(){
nav();
};
//nav导航
function nav(){
var arr = [pos($('div1')).top,pos($('div2')).top,pos($('div3')).top,pos($('div4')).top,pos($('div5')).top,pos($('div6')).top,pos($('div7')).top,pos($('div8')).top];
var oUl=getByClass('nav')[0];
var aLi = oUl.getElementsByTagName('li');
console.log(aLi.length);
(function(){
aLi[0].style.background ='#fd8200';
aLi[0].s=true;
})();
for(var i=0; i<aLi.length;i++){
aLi[i].onmouseover = function(){
if(!this.s){
this.style.background='#fd8200'
}
}
aLi[i].onmouseout = function(){
if(!this.s){
this.style.background='';
}
}
aLi[i].index=i;
aLi[i].onclick=function(){
num = this.index;
for(var i=0; i<aLi.length;i++){
aLi[i].style.background='';
aLi[i].s='';
}
this.style.background='#fd8200';
this.s=true;
window.onscroll=function(){

}
}
}
document.onmousewheel=fnMouse;//滚轮事件
if(document.addEventListener){
document.addEventListener('DOMMouseScroll',fnMouse,false);
}
function fnMouse(){
for(var i=0;i<arr.length;i++){
aLi[i].style.background='';
console.log("y "+scrollY());
console.log("arr "+arr[i]);
if(scrollY()>arr[i] && scrollY()<arr[i+1]){
aLi[i].style.background='#fd8200';
};
if(scrollY()>arr[arr.length-1]){
aLi[arr.length-1].style.background='#fd8200';
};
}
}
}
//  滚动条高
function scrollY() {
return document.documentElement.scrollTop || document.body.scrollTop;
};
//获取className
function getByClass(sClass,parent){
var aEles=(parent || document).getElementsByTagName('*');
var re = new RegExp('\\b'+ sClass +'\\b');
var arr=[];
for(var i=0;i<aEles.length;i++){
if(re.test(aEles[i].className)){
arr.push(aEles[i])
}
}
return arr;
}
//获取ID
function $(id){
return document.getElementById(id);
}
//obj到页面顶部实际距离
function pos(obj){
var result = {left:0,top:0};
while(obj){
result.top +=obj.offsetTop;
result.left +=obj.offsetLeft;
obj=obj.offsetParent;
}
return result;
}

演示

原创文章:javascript练习:导航随内容滚动而跟随变化 ,未经许可,禁止转载,©版权所有
原文出处:前端开发博客 (http://caibaojian.com/menu-scroll-active.html)