我有一个单页网站,有固定的浮动导航。我希望能够通过向相关导航标签添加一类“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");
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)