使用jQuery更改取决于滚动位置的类 [英] Use jQuery to change a class dependent on scroll position
问题描述
我有一个单页网站,该网站具有固定的浮动导航.我希望能够通过在相关导航中添加一个标记为"on"的类来突出显示用户位于哪个部分.
I have a single page website which has a fixed floating nav. I want to be able to highlight which section the user is on by adding a class of say "on" to the relevant navigation a tag.
当用户不再位于该部分上并且需要在导航栏中反映新的当前部分时,将需要删除此类.
This class will need to be removed when the user is no longer on that section and the new current section then needs to be reflected in the nav.
这不能通过单击功能来完成,因为用户仍然可以只在页面上上下滚动.我知道这个方法是否可以完成,或者因为我的jQuery受限制而从哪里开始.
This can't be done via a click function, as the user could still just scroll up and down the page. I have know idea if this can even be done or where to start as my jQuery is VERY limited.
任何帮助将不胜感激.
这是我当前的网页,没有任何有效的导航突出显示: http ://ec2.dragonstaff.com/www.creativegems.co.uk/
Here is my current webpage, which doesn't have any active nav highlighting: http://ec2.dragonstaff.com/www.creativegems.co.uk/
推荐答案
这似乎与您的网站兼容:
This seems to work with your site:
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");
}
});
这篇关于使用jQuery更改取决于滚动位置的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!