http://jsfiddle.net/motocomdigital/gUWdJ/
我是后一个jQuery滚动技术讨好,我想,以适应我的项目。
请参阅我的项目,例如这里提琴http://jsfiddle.net/motocomdigital/gUWdJ/
目前,你可以看到我的导航链接相对滚动动画自动向<section>
的。
我的问题是,使用$(window).scroll
方法,我怎么可以添加一个.active
类我的nav a
当段到达窗口的顶部?
因此,举例来说,如果用户向下滚动页面(而不是导航链接),我想加入活动类相对导航链接。 说明你在页面上的位置。
活动类将不得不被删除,然后添加每次我猜为用户向下滚动页面时。
你还必须考虑到固定导航栏28px高度,偏移顶部窗口。
任何人都可以请告诉我的技术,我可以尝试使用或修改,或者告诉我用我的jsfiddle :)
任何帮助将不胜感激,谢谢提前!
http://jsfiddle.net/motocomdigital/gUWdJ/
![](https://www.manongdao.com/static/images/pcload.jpg)
如果你希望一个更通用的功能:
观看演示
$(window).scroll(function() {
var windscroll = $(window).scrollTop();
if (windscroll >= 100) {
$('nav').addClass('fixed');
$('.wrapper section').each(function(i) {
if ($(this).position().top <= windscroll - 100) {
$('nav a.active').removeClass('active');
$('nav a').eq(i).addClass('active');
}
});
} else {
$('nav').removeClass('fixed');
$('nav a.active').removeClass('active');
$('nav a:first').addClass('active');
}
}).scroll();
你可以这样说: http://jsfiddle.net/gUWdJ/1/
$(window).scroll(function() {
if ($(this).scrollTop() < $('section[data-anchor="top"]').offset().top) {
$('nav a').removeClass('active');
}
if ($(this).scrollTop() >= $('section[data-anchor="top"]').offset().top) {
$('nav a').removeClass('active');
$('nav a:eq(0)').addClass('active');
}
if ($(this).scrollTop() >= $('section[data-anchor="news"]').offset().top) {
$('nav a').removeClass('active');
$('nav a:eq(1)').addClass('active');
}
if ($(this).scrollTop() >= $('section[data-anchor="products"]').offset().top) {
$('nav a').removeClass('active');
$('nav a:eq(2)').addClass('active');
}
if ($(this).scrollTop() >= $('section[data-anchor="contact"]').offset().top) {
$('nav a').removeClass('active');
$('nav a:eq(3)').addClass('active');
}
});
我继续修改我的脚本关闭A.沃尔夫的,因为我要确保我的菜单项点燃了一个负顶级差异,而不是为0。这个工作不是创建一个单独的功能好了很多,并避免了创建单击事件为每个菜单项。 我还要修改此脚本,以考虑该菜单中的最后一项,它应该自动如果第二到最后一个项目是突出显示。 我想,我的是非常相似,但不同的,因为我处理了我的主要亮点功能之外我的每个循环。 关于我修改的另一个伟大的事情是占了有一个菜单项的内部链接的内部图像,并占了元素的高度,当该元素的底部点击该页面的顶部,也就是当亮点应该结束一个新的做了。
function highlight(item)
{
var itemTop = jQuery(item).position().top;
var windowTop = jQuery(window).scrollTop();
var topDifference = (windowTop - itemTop);
var itemHeight = jQuery(item).height();
var bottomDifference = topDifference - itemHeight;
var menuId = jQuery('#nav-icons li a').attr('href');
if (menuId = item)
{
if(topDifference > -1 && bottomDifference < 0)
{
jQuery("#nav-icons li a[href='" + item + "']").parent().addClass('active');
jQuery("#nav-icons li a[href!='" + item + "']").parent().removeClass('active');
}
else {
jQuery("#nav-icons li a[href='" + item + "']").parent().removeClass('active');
}
}
}
jQuery('#nav-icons li a').each(function(){
var eachAttr = jQuery(this).attr('href');
highlight(eachAttr);
});
文章来源: jquery scroll, change navigation active class as the page is scrolling, relative to sections