【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;
}
新聞熱點
疑難解答
圖片精選