Ich habe eine Sidebar als Subnavigation und angefügt einige benutzerdefinierte Javascript, um die Navlinks innerhalb es zu markieren, während der Benutzer scrollt die Abschnitte. Ich habe dieses Javascript in meine js-Hauptdatei eingefügt. Die Seitenleiste ist nicht auf jeder Seite enthalten. Für die Leistung würde ich gerne wissen, ob das angehängte Scroll-Ereignis in dieser Sidebar auch auf einer Site ausgelöst wird, auf der die Sidebar nicht enthalten ist, oder wird dieses Skript auf diesen Sites ignoriert?Wird ein Scroll-Ereignis auch ausgelöst, wenn das Targeting-Element nicht existiert?
// waypoint for fixed sidebar
$('.tg-desktop__accordionWrapper').waypoint(function (direction) {
if (direction === 'down') {
$(this.element).addClass('tg-accordion__sidebar--fixed');
} else {
$(this.element).removeClass('tg-accordion__sidebar--fixed');
}
});
// cache the navigation links
var $navigationLinks = $('.tg-accordion__sidebarLink');
// cache (in reversed order) the sections
var $sections = $($(".tg-accordion__text").get().reverse());
// map each section id to their corresponding navigation link
var sectionIdTonavigationLink = {};
$sections.each(function() {
var id = $(this).attr('id');
sectionIdTonavigationLink[id] = $('.tg-accordion__sidebarLink[href=#' + id + ']');
});
// throttle function, enforces a minimum time interval
function throttle(fn, interval) {
var lastCall, timeoutId;
return function() {
var now = new Date().getTime();
if (lastCall && now < (lastCall + interval)) {
// if we are inside the interval we wait
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
lastCall = now;
fn.call();
}, interval - (now - lastCall));
} else {
// otherwise, we directly call the function
lastCall = now;
fn.call();
}
};
}
function highlightNavigation() {
// get the current vertical position of the scroll bar
var scrollPosition = $(window).scrollTop();
// iterate the sections
$sections.each(function() {
var currentSection = $(this);
// get the position of the section
var sectionTop = currentSection.offset().top;
// if the user has scrolled over the top of the section
if (scrollPosition >= sectionTop) {
// get the section id
var id = currentSection.attr('id');
// get the corresponding navigation link
var $navigationLink = sectionIdTonavigationLink[id];
// if the link is not active
if (!$navigationLink.hasClass('active')) {
// remove .active class from all the links
$navigationLinks.removeClass('active');
// add .active class to the current link
$navigationLink.addClass('active');
}
// we have found our section, so we return false to exit the each loop
return false;
}
});
}
$(window).scroll(throttle(highlightNavigation,100));
danke! machte meinen Tag, dachte nicht über die Längenoption für die Funktion nach! Ich denke, das sollte immer gemacht werden, wenn Scroll- oder Resize-Handler nur gelegentlich benutzt werden :-) Merry Christmas @ Roamer-1888 – DoUtDes