【发布时间】:2017-12-24 18:03:52
【问题描述】:
我有一个侧边栏作为子导航,并附加了一些自定义 javascript 以在用户向下滚动部分时突出显示其中的导航链接。我将此 javascript 包含在我的主 js 文件中。侧边栏未包含在每个页面上。对于性能我想知道,如果附加到此侧边栏的滚动事件也会在不包含侧边栏的站点上触发,或者在这些站点上忽略这段脚本?
// 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) );
【问题讨论】:
标签: jquery performance events scroll