很多时候我们想让导航栏超出窗口的位置后边固定在最上方不再移动,方便用户操作。
html代码如下
<div id="nav"><ul> <!--选项卡--><li><a href="#x">首页</a></li><li><a href="#">集合</a></li><li><a href="#">图文</a></li><li>...</li><li>...</li><li>...</li></ul></div>
js代码如下,占位符的作用是为了让导航栏设置为fixed时不那么突兀。
var tit = document.getElementById("nav");//占位符的位置var rect = tit.getBoundingClientRect();//获得页面中导航条相对于浏览器视窗的位置var inser = document.createElement("div");tit.parentNode.replaceChild(inser,tit);inser.appendChild(tit);inser.style.height = rect.height + "px"; var titleTop = tit.offsetTop; //获取距离页面顶端的距离document.onscroll = function(){//滚动事件var btop = document.body.scrollTop||document.documentElement.scrollTop; //获取当前滚动的距离if(btop>titleTop){//如果滚动距离大于导航条据顶部的距离tit.className = "clearfix fix";//为导航条设置fix$("#nav>ul").css("background-color","#e1e5e8"); //更改导航栏吸顶时得颜色 ,如不需要可删除}else{//移除fixedtit.className = "clearfix";$("#nav>ul").css("background-color","white"); //恢复正常颜色}}