我有以下问题:
我想实现一些逻辑来在滚动时在导航栏中的列表元素上设置事件类。我使用了这个片段:
$(window).bind('scroll', function () {
var scrollPos = $(window).scrollTop() + 100;
$('#nav-menu a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
currLink = currLink.parent();
if (refElement.position().top <= scrollPos) { //&& refElement.position().top + refElement.height() > scrollPos
$('.nav > li').removeClass("active");
currLink.addClass("active");
} else {
currLink.removeClass("active");
}
});
});
它在我滚动时工作正常,因此在我单击导航栏内的链接时也工作正常。假设我有 5 个链接指向 5 个不同的 div。假设我当前位于第一个 div 的位置。
现在我单击最后一个链接,它会滚动浏览 div。但是现在,当我滚动时,中间的每个链接都会获得事件类。
您能否建议一种解决方法来跳过中间的链接?
编辑:这是点击滚动代码部分:
// Page scroll
$('a.page-scroll').click(function () {
$(".nav > li").removeClass("active");
// $(this).parent().addClass("active");
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') &&
location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 40
}, 900);
return false;
}
}
});
最佳答案
根据我对上述问题的评论修改了您的代码。让我知道这是否有效。我评论了我的修改,因此您可以为 --CapitalQ
使用 CMD/CTRL+F。
$(window).bind('scroll', function () {
var scrollPos = $(window).scrollTop() + 100;
$('#nav-menu a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
currLink = currLink.parent();
if (refElement.position().top <= scrollPos) {
$('.nav > li').removeClass("active");
// added a check here to only add "active" if body not scrolling --CapitalQ
if (!$('body').hasClass('scrolling')) {
currLink.addClass("active");
}
}
else {
currLink.removeClass("active");
}
});
});
$('a.page-scroll').click(function () {
// Add scrolling class to body --CapitalQ
$('body').addClass('scrolling');
$(".nav > li").removeClass("active");
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 40
}, 900, function () {
// added callback to jQ animate function --CapitalQ
$('body').removeClass('scrolling');
$(this).parent().addClass('active');
});
return false;
}
}
});
关于javascript - 滚动时跳过某些元素的事件类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40707602/