我需要帮助来弄清楚我的 javascript 发生了什么。当你在页面的那部分时,我有一些代码应该使导航链接具有事件类,但它只适用于几个链接,并且它也会在你滚动时闪烁而不是一直保持事件状态你在页面的那个部分。有关示例,请参阅 JSFiddle https://jsfiddle.net/7szpuqsr/ -- 如果你慢慢滚动,你可以看到“主页”是如何暂时激活的。我试图让每个链接在您单击它时以及当您位于页面的整个部分时都具有事件类。
我还有一个 javascript 粘性导航栏和流畅的滚动功能,所以我不知道是否有任何障碍?在此先感谢您的帮助。
这是我尝试用于事件类的 Javascript:
var sections = $('section')
, nav = $('nav')
, nav_height = nav.outerHeight();
$(window).on('scroll', function () {
var cur_pos = $(this).scrollTop();
sections.each(function() {
var top = $(this).offset().top - nav_height,
bottom = top + $(this).outerHeight();
if (cur_pos >= top && cur_pos <= bottom) {
nav.find('a').removeClass('active');
sections.removeClass('active');
$(this).addClass('active');
nav.find('a[href="#'+$(this).attr('id')+'"]').addClass('active');
}
});
});
nav.find('a').on('click', function () {
var $el = $(this)
, id = $el.attr('href');
$('html, body').animate({
scrollTop: $(id).offset().top - nav_height
}, 500);
return false;
});
最佳答案
是这样的吗?我无法在我的机器上以视觉方式重现闪烁,但我可以看到该类在滚动时不断被删除/添加
https://jsfiddle.net/7szpuqsr/1/
主要更改,我在您的部分中添加了一个类,您的部分太多,但是按照您的代码的工作方式,向这些部分添加一个类要容易得多,示例如下
<section id="home" class="section">
var sections = $('.section')
获取节类
更新了这部分的 js 以检查事件类
if (cur_pos >= top && cur_pos <= bottom) {
if(!$(this).hasClass("active")) {
nav.find('a').removeClass('active');
sections.removeClass('active');
$(this).addClass('active');
nav.find('a[href="#'+$(this).attr('id')+'"]').addClass('active');
}
}
您还可以将 $(this)
缓存到节循环内的变量中,例如
var $this = $(this);
然后在循环的剩余部分使用$this
这是 hasClass
的文档 https://api.jquery.com/hasclass/
关于javascript - 使用 javascript 滚动时如何保持类事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44507624/