我有一个单页网站,其中有一个固定的浮动导航。我希望能够通过在相关导航标签中添加一个" on“类来突出显示用户所在的部分。
当用户不再位于该部分,并且新的当前部分需要反映在nav中时,将需要删除此类。
这不能通过点击功能来完成,因为用户仍然可以上下滚动页面。我知道这是不是可以做到,或者从哪里开始,因为我的jQuery非常有限。
任何帮助都将不胜感激。
这是我当前的网页,它没有任何活动的导航突出显示:http://ec2.dragonstaff.com/www.creativegems.co.uk/
发布于 2010-10-09 02:46:59
这似乎适用于你的网站:
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");
}
});发布于 2010-10-09 02:17:16
你可以用以下命令抓取窗口的scrollTop
var scrollTop=$(window).scrollTop();http://api.jquery.com/scrollTop
然后遍历内容<div>,并累加它们的高度,直到得到一个足够接近scrollTop的值。关于如何处理重叠,您可能需要进行一些实验。
一旦您发现您的滚动到您的项目组合的内容,您可以将相关的类添加到nav元素。
发布于 2013-04-19 23:27:33
只是在这里添加这个作为替代:
有一个名为Waypoints的jQuery插件。实现起来非常简单。他们网站上的例子是:
$('.thing').waypoint(function(direction) {
alert('Top of thing hit top of viewport.');
});所以,只要你知道这个元素的名字是什么,路点就会变得很愚蠢,实现起来也很简单。
https://stackoverflow.com/questions/3893124
复制相似问题