问题
I have implemented the code to change "active" class of menu when page scrolling.
Here is the code I use to manage this behavior (extract from main.js file) :
$("a.nav-link").click(function(e){
$('html, body').animate({
scrollTop: $(e.target.hash).offset().top - 15
});
$(this).parent().siblings().removeClass('active');
var $parent = $(this).parent();
$parent.addClass('active');
});
window.addEventListener('load', () => {
const headings = document.querySelectorAll('section');
var topMenu = $(".navbar-nav"),
topMenuHeight = topMenu.outerHeight()+15,
menuItems = topMenu.find("a");
document.addEventListener('scroll', (e) => {
headings.forEach(ha => {
const rect = ha.getBoundingClientRect();
if(rect.top > 0 && rect.top < 150) {
if(ha.id != "presentation")
{
const location = window.location.toString().split('#')[0];
history.replaceState(null, null, location + '#' + ha.id);
//console.log(menuItems.filter("[href='/ea-jamm/#"+ha.id+"']").parent()[0].classList);
if(menuItems.filter("[href='/ea-jamm/#"+ha.id+"']").parent()[0].classList.contains("active")){
}
else
{
menuItems
.parent().removeClass("active")
.end().filter("[href='/ea-jamm/#"+ha.id+"']").parent().addClass("active");
}
}
else
{
menuItems
.parent().removeClass("active")
const location = window.location.toString().split('#')[0];
history.replaceState(null, null, location);
}
}
});
});
});
You can constat the behavior here : http://mehdigallois.fr/ea-jamm/
However, when i scroll the page very quickly, the change of "active" class in the menu is not reliable and sometimes the first menu item is active while the page is at bottom. (in this case, it is the last menu item h which has to be "active")
How can I make the change of "active" class in the menu more reliable when scrolling ?
Moreover, when I scroll the page completely at bottom on fullscreen device (not mobile or tablet), the last menu item "Nous contacter" does not have the "active" class : it still the second to last which has the "active" class. Same when i click on the last menu item. (Check the behavior for yourselves.)
来源:https://stackoverflow.com/questions/65414249/make-the-change-of-active-class-in-the-menu-more-reliable-when-scrolling