问题描述
我只有一个页面滚动网站,并且想更改滚动和单击时链接的活动类别。 我从该网站上找到了一些很棒的摘要,它们完成了一半的工作(对于那些感兴趣的人,这也可以平滑滚动):
$(document).ready(function () { $(document).on("scroll", onScroll); //smoothscroll $('a[href^="#"]').on('click', function (e) { e.preventDefault(); $(document).off("scroll"); $('a').each(function () { $(this).removeClass('active'); }) $(this).addClass('active'); var target = this.hash, menu = target; $target = $(target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top+2 }, 500, 'swing', function () { window.location.hash = target; $(document).on("scroll", onScroll); }); }); }); function onScroll(event){ var scrollPos = $(document).scrollTop(); $('a').each(function () { var currLink = $(this); var refElement = $(currLink.attr("href")); if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) { $('a').removeClass("active"); currLink.addClass("active"); } else{ currLink.removeClass("active"); } }); }
出现问题是因为我有多个菜单,这些菜单在不同的屏幕尺寸下可见。 我正在设法同时更改两个菜单项上的活动类。
任何建议将不胜感激
1楼
我自己解决了这个问题,但我欢迎更干净的解决方案。 我只是复制了代码:
$(document).ready(function () { $(document).on("scroll", onScroll); //smoothscroll $('#nav-minor a[href^="#"]').on('click', function (e) { e.preventDefault(); $(document).off("scroll"); $('#nav-minor a').each(function () { $(this).removeClass('active'); }) $(this).addClass('active'); var target = this.hash, menu = target; $target = $(target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top+2 }, 500, 'swing', function () { window.location.hash = target; $(document).on("scroll", onScroll); }); }); }); function onScroll(event){ var scrollPo = $(document).scrollTop(); $('#nav-minor a').each(function () { var currLink = $(this); var refElement = $(currLink.attr("href")); if (refElement.position().top <= scrollPo && refElement.position().top + refElement.height() > scrollPo) { $('#nav-minor a').removeClass("active"); currLink.addClass("active"); } else{ currLink.removeClass("active"); } }); }
尽管辅助菜单具有不同的ID:
$(document).ready(function () { $(document).on("scroll", onScroll); //smoothscroll $('#nav-main li a[href^="#"]').on('click', function (e) { e.preventDefault(); $(document).off("scroll"); $('#nav-main li').each(function () { $(this).removeClass('active'); }) $(this).addClass('active'); var target = this.hash, menu = target; $target = $(target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top+2 }, 500, 'swing', function () { window.location.hash = target; $(document).on("scroll", onScroll); }); }); }); function onScroll(event){ var scrollPos = $(document).scrollTop(); $('#nav-main li a').each(function () { var currItem = $(this); var refElement = $(currItem.attr("href")); if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) { $('#nav-main li a').removeClass("active"); currItem.addClass("active"); } else{ currItem.removeClass("active"); } }); }
如果有人对此有更好的答案,将不胜感激。 现在纯粹出于学术原因:-)`