jQuery頁面定位導航滾動插件jquery.nav 參考:http://www.dowebok.com/demo/122/ 下載
原生JS 實現頁面滾動時導航智能定位 參考:https://m.jb51.net/article/113085.htm
<div class="container">
<div class="wrapper">
<div class="section" id="section1">section1</div>
<div class="section" id="section2">section2</div>
<div class="section" id="section3">section3</div>
<div class="section" id="section4">section4</div>
<div class="section" id="section5">section5</div>
</div>
<nav>
<a href="#section1" rel="external nofollow" class="current">section1</a>
<a href="#section2" rel="external nofollow" >section2</a>
<a href="#section3" rel="external nofollow" >section3</a>
<a href="#section4" rel="external nofollow" >section4</a>
<a href="#section5" rel="external nofollow" >section5</a>
</nav>
</div>
頁面滾動時導航定位
js代碼如下:
var $navs = $('nav a'), // 導航
$sections = $('.section'), // 模塊
$window = $(window),
navLength = $navs.length - 1;
$window.on('scroll', function() {
var scrollTop = $window.scrollTop(),
len = navLength;
for (; len > -1; len--) {
var that = $sections.eq(len);
if (scrollTop >= that.offset().top) {
$navs.removeClass('current').eq(len).addClass('current');
break;
}
}
});
效果如下:

不難看出,基本原理就是在window滾動的時候,依次將模塊從后向前遍歷,如果window的滾動高度大於或等於當前模塊的距頁面頂部的距離,則將當前模塊對應的導航突出顯示,並且不再繼續遍歷
點擊導航定位頁面
除了這種需求外,還有另一種需求,就是點擊導航定位到導航所對應模塊的頂部。
代碼如下:
$navs.on('click', function(e) {
e.preventDefault();
$('html, body').animate({
'scrollTop': $($(this).attr('href')).offset().top
}, 400);
});
效果如下:

=====================
offset() 方法返回或設置匹配元素相對於文檔的偏移(位置)。該方法返回的對象包含兩個整型屬性:top 和 left,以像素計。此方法只對可見元素有效
獲得 <p> 元素當前的偏移:
$(".btn1").click(function(){
x=$("p").offset();
$("#span1").text(x.left);
$("#span2").text(x.top);
});
設置所有匹配元素的偏移坐標:
$("p").offset({top:100,left:0});
animate() 方法執行 CSS 屬性集的自定義動畫。 參考 http://www.w3school.com.cn/jquery/effect_animate.asp
改變 "div" 元素的高度:
$(".btn1").click(function(){
$("#box").animate({height:"300px"});
});
scrollTop() 方法返回或設置匹配元素的滾動條的垂直位置。
scrollLeft() 方法返回或設置匹配元素的滾動條的水平位置。
scroll top或者 left offset 指的是滾動條相對於其頂部和左邊的偏移。
設置 <div> 元素中滾動條的水平偏移:
$(".btn1").click(function(){
$("div").scrollLeft(100);
})
獲取
$(".btn1").click(function(){
alert($("div").scrollLeft()+" px");
});
