jq方法
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>地狗購(gòu)物網(wǎng)——網(wǎng)頁(yè)定位導(dǎo)航效果</title>
<style>
* {
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: 16px;
font-weight: bold;
border-bottom: 2px solid #0088bb;
margin-bottom: 10px;
}
#content .item li {
display: inline;
margin-right: 10px;
}
#content .item li a img {
width: 230px;
height: 230px;
border: none;
}
/*請(qǐng)補(bǔ)充此處代碼屯吊,讓導(dǎo)航菜單在右側(cè)絕對(duì)定位顯示*/
#menu {
position: fixed;
left: 50%;
top: 100px;
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-decoration: none;
text-align: center;
}
#menu ul li a:hover,
#menu ul li a.current {
color: #fff;
background: #0088bb;
}
/*ie6 不支持 fixed*/
/*ie6 hack*/
* html, * html body {
background-image: url(about:blank);
background-attachment: fixed;
}
* html #menu {
/*position: fixed;*/
position: absolute;
top: expression(((e=document.documentElement.scrollTop)?e:document.body.scrollTop)+100+'px');
}
</style>
<script src="js/jquery-1.7.1.min.js"></script>
<script>
$(function(){
$(window).scroll(function(){
// 獲取滾動(dòng)條滾動(dòng)距離
var top = $(document).scrollTop();
console.log(top)
var menu = $("#menu")
// 當(dāng)前所在樓層的id
var currentId = "";
// 獲取每一個(gè)item距離頂部的top距離,和滾動(dòng)條的top比較帜讲,
// 如果top大了就獲取id祸泪,直到最終小了停止
var items = $("#content").find(".item") ; items.each(function(){
var m = $(this);
var itemTop = m.offset().top;
// 通過(guò)循環(huán)的判斷峭范,會(huì)鎖定最終的悔详,把前面的覆蓋掉,-200為了體驗(yàn)更好
if (top > itemTop - 200){
currentId = "#"+m.attr("id");
}
})
//給相應(yīng)樓層的a 設(shè)置 current撞反,取消其他鏈接的current
var currentLink = menu.find(".current")
// 排他
if (currentId && currentLink.attr("href") !=currentId) {
currentLink.removeClass("current");
menu.find ("[href="+ currentId + "]").addClass("current")
}
})
})
js方法