我有一个单页网站,它有一个固定的浮动导航.我希望能够通过在相关导航标签上添加"on"类来突出显示用户所在的部分.
当用户不再使用该部分时,需要删除此类,然后需要在导航中反映新的当前部分.
这不能通过点击功能完成,因为用户仍然可以只在页面上下滚动.我知道是否可以这样做或者从哪里开始因为我的jQuery非常有限.
任何帮助将非常感激.
这是我当前的网页,没有任何主动导航突出显示:http://ec2.dragonstaff.com/www.creativegems.co.uk/
这似乎适用于您的网站:
var $sections = $('section'); // all content sections
var $navs = $('nav > ul > li'); // all nav sections
var topsArray = $sections.map(function() {
return $(this).position().top - 300; // make array of the tops of content
}).get(); // sections, with some padding to
// change the class a little sooner
var len = topsArray.length; // quantity of total sections
var currentIndex = 0; // current section selected
var getCurrent = function( top ) { // take the current top position, and see which
for( var i = 0; i < len; i++ ) { // index should be displayed
if( top > topsArray[i] && topsArray[i+1] && top < topsArray[i+1] ) {
return i;
}
}
};
// on scroll, call the getCurrent() function above, and see if we are in the
// current displayed section. If not, add the "selected" class to the
// current nav, and remove it from the previous "selected" nav
$(document).scroll(function(e) {
var scrollTop = $(this).scrollTop();
var checkIndex = getCurrent( scrollTop );
if( checkIndex !== currentIndex ) {
currentIndex = checkIndex;
$navs.eq( currentIndex ).addClass("selected").siblings(".selected").removeClass("selected");
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9844 次 |
| 最近记录: |