我需要幫助指出我的javascript發生了什麼。我有一些代碼,當你在頁面的那一部分時,應該讓導航鏈接有一個活動的類,但它只是爲一對夫婦鏈接工作,當你滾動而不是在整個時間保持活動時它也會閃爍你在頁面的那一部分。以JSFiddle爲例https://jsfiddle.net/7szpuqsr/ - 如果您慢速滾動,您可以看到「家」在一瞬間變得活躍。我試圖讓每個鏈接在您點擊它時以及在頁面的整個部分都有活動類。如何在使用javascript滾動時保持課程活動?
我也有一個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;
});
那麼你的代碼刪除並添加滾動的活動類,所以它要走了閃爍。你可以設置一個條件,如果活動班已經在那裏,不要做任何事情 – Huangism
你能告訴我那是什麼樣子嗎?我仍然在學習JavaScript。 – SShine2