【JS-实现导航栏悬停】
【JS-实现导航栏悬停(续)】
用Jquery重新写完这个页面之后,发现原来的方法还有是有几个问题:
1.首先Js代码冗余,导航条上的Tab是用js实现跳转而不是超链接;
2.还有导航条本身用fixed定位,但没有被设置为水平居中,而是在JS中更改left值使其居中。
问题2就导致了,当浏览器窗口尺寸发生变化的时候,浏览器中的div的位置都发生了变化,也就导致了没法通过页面中的div动态的给已fixed定位的导航条来定位。
最终的代码更改如下:
test.html
复制代码 代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript" src="test.js"></script>
<link type="text/css" href="test.css"></link>
<title>Test</title>
</head>
<body>
<div>
<div>1</div>
<div>
<a href="#content_div3"><div>tab1</div></a>
<a href="#content_div4"><div>tab2</div></a>
<a href="#content_div5"><div>tab3</div></a>
<a href="#content_div6"><div>tab4</div></a>
</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
</div>
</body>
</html>
复制代码 代码如下:
//记录导航条原来在页面上的位置
var naviga_offsetTop = 0;
//使导航条,悬停在顶部
function naviga_stay_top(){
//获取滚动距离
var scrollTop = $(document).scrollTop();
//如果向下滚动的距离大于原来导航栏离顶部的距离
//直接将导航栏固定到可视区顶部
if( scrollTop > naviga_offsetTop ){
$("#nav").css({"top": "0px"});
} else {
//如果向下滚动的距离小原来导航栏离顶部的距离,则重新计算导航栏的位置
$("#nav").css({"top": naviga_offsetTop - scrollTop + "px"});
}
}
function onload_function(){
//记录初始状态导航栏的高度
naviga_offsetTop = $("#nav").attr("offsetTop");
//绑定滚动和鼠标事件
$(window).bind("scroll", naviga_stay_top);
$(window).bind("mousewheel",naviga_stay_top);
$(document).bind("scroll", naviga_stay_top);
$(document).bind("mousewheel",naviga_stay_top);
}
$(document).ready( onload_function );
复制代码 代码如下:
div.main{
width: 800px;
background: #CCC;
margin: 10px auto 0;
position: relative;
}
div.content{
width: 800px;
height: 400px;
background: yellow;
margin: 10px auto 0;
}
div.navigation{
width: 800px;
height: 40px;
background: red;
margin: 0 auto;
top: 400px;
left:50%;
position: fixed;
margin-left:-400px;
}
div.tab{
width: 195px;
height: 40px;
background: blue;
float: left;
margin-left: 5px;
}
新闻热点
疑难解答
图片精选