基于JQuery和原生JavaScript实现网页定位导航特效(2)

<script> //定义getByClassName函数,让函数实现根据className获取对象并返回 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; } //定义hasClass函数,确认对象是否包含对应的class function hasClass(obj, cls) { return obj.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)")); } //定义removeClass函数,让函数实现删除对象的class function removeClass(obj, cls) { if (hasClass(obj, cls)) { //remove var reg = new RegExp("(\\s|^)" + cls + "(\\s|$)"); obj.className = obj.className.replace(reg, ""); } } //定义addClass函数,让函数实现给对象增加class function addClass(obj, cls) { if (!hasClass(obj, cls)) { obj.className += " " + cls; } } //页面加载完毕执行以下函数 window.onload = function() { //页面滚动时,执行以下函数 window.onscroll = function() { var top = document.documentElement.scrollTop || document.body.scrollTop; 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; } } //给正确的menu下的a元素class赋值current if (currentId) { for (var j = 0; j < menus.length; j++) { var _menu = menus[j]; var _href = _menu.href.split("#"); if (_href[_href.length - 1] != currentId) { removeClass(_menu, "current"); } else { addClass(_menu, "current"); } } } } } </script>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwygpz.html