var top 法一法二不应该等价的么,为什么法二运行不了?
<script>
//根据className获取元素,解决ie没有getElementsByClassName
function getByClassName(obj,cls) {
var elements = obj.getElementsByTagName("*");
var result = [];//声明数组
for (var i = 0; i < elements.length; i++) {
if(elements[i].className == cls){//如果后面有多个className这个就不行了
result.push(elements[i]);
}
}
return result;
}
window.onload=function(){
//监听滚动事件
window.onscroll=function(){
//法一
var top = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
//法二
/*if(document.documentElement.scrollTop){
top = document.documentElement.scrollTop;
}else{
top = document.body.scrollTop;
}*/
//法三
// var top = document.documentElement.scrollTop || document.body.scrollTop;
//前面兼容IE,后面兼容chrome
var menus = document.getElementById('menu').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 = _item.id;
}else{
break;//直接跳出for循环,如果是continue则表示 继续执行下一个for循环,不执行后面的代码
}
}
if(currentId){
for (var j = 0; j < menus.length; j++) {
var _menus = menus[j];
var _href = _menus.href.split("#");
/*js中利用_menus.href获取的是整个网址带上href,所以这里用split通过#分割成两个数组
file:///D:/Demo/jquery/网页定位导航特效/网页定位导航(源代码)/demo.html#item2*/
if (_href[_href.length - 1] != currentId) {
_menus.className="";
}else{
_menus.className="current";
}
}
}
};
};
</script>