本文实例为大家分享了js网页定位导航的具体代码,供大家参考,具体内容如下
一个循环判断当前滚动到的位置,另一个循环遍历导航条判断其id是否与滚动到的位置相同
效果如图:
实现代码:
地狗购物网--网页定位导航效果*{
margin: 0;
padding: 0;
}
body{
font-size: 12px;
line-height: 1.7;
}
li{
list-style: none;
}
#content{
width: 800px;
margin: 0 auto;
padding: 20px;
}
#content h1{
color: #0088bb;
}
#content .item{
padding: 20px;
margin-bottom: 20px;
border: 1px dotted #0088bb;
}
#content .item h2{
font-size: 12px;
font-weight: bold;
border-bottom: 2px solid #0088bb;
margin-bottom: 10px;
}
#content .item li{
display: inline;
margin-left:10px ;
}
#content .item li a img{
width: 230px;
height: 230px;
border: none;
}
#menu{
position: fixed;
top: 100px;
left: 50%;
margin-left: 400px;
width: 80px;
}
#menu ul li a{
display: block;
margin: 5px 0;
font-size: 14px;
font-weight: bold;
color: #333;
width: 80px;
height: 50px;
line-height: 50px;
text-align: center;
text-decoration: none;
}
#menu ul li a:hover{
color: #fff;
background: #0088bb;
}
#menu ul li .current{
color: #fff;
background: #0088bb;
}
window.onload = function(){
window.οnscrοll=function(){
var top = document.documentElement.scrollTop || document.body.scrollTop;
var menus = document.getElementById("menu").getElementsByTagName("a");
var items=document.getElementById("content").getElementsByClassName("item");
var currentId="";
for(var i=0;i
var _item=items[i];
var _itemTop = _item.offsetTop;
if(top>_itemTop - 200){
currentId=_item.id;
}else{
break;
}
}
if(currentId!=""){
//给正确的menu下的a元素class赋值
for(var j=0;j
var _menu=menus[j];
var _href=_menu.href.split("#");//因为只通过href获取的链接为一长串链接,需要通过#分成数组
if(_href[_href.length-1]!=currentId){
_menu.className = "";
}else{
_menu.className = " current";
}
}
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。