我有一个奇怪的问题,当用户滚动或单击每个菜单项时,我使用 jQuery 自动将“活动”类添加到内部菜单(并更新 url)。滚动时它工作正常,但单击时它会加粗并更新单击的项目上方项目的 url,我不明白为什么......
我的菜单设置如下:
<ul>
<li><a href="#1" data-id="1" class="toc-link">link 1</a></li>
<li><a href="#2" data-id="2" class="toc-link">link 2</a></li>
...etc
</ul>
内容设置为:
<h2 id="1">title 1<h2>
<p>content</p>
<h2 id="2">title 2<h2>
<p>content</p>
...etc
jQuery 脚本:
jQuery(document).ready(function() {
// Update the active header and URL on click
jQuery('.toc-link').click(function(e) {
e.preventDefault();
var activeId = jQuery(this).attr('data-id');
var url = window.location.href.split('#')[0];
var newUrl = url + '#' + activeId;
window.history.pushState('', document.title, newUrl);
jQuery('.toc-link.active').removeClass('active');
jQuery(this).addClass('active');
// Scroll to corresponding header
var headerTop = jQuery('#' + activeId).offset().top;
jQuery('html, body').animate({ scrollTop: headerTop }, 500);
});
// Update the active header and URL on scroll
jQuery(window).scroll(function() {
var scrollPos = jQuery(window).scrollTop();
var activeId = null; // Initialize activeId to null
jQuery('h2').each(function() {
var headerTop = jQuery(this).offset().top;
var id = jQuery(this).attr('id');
if (scrollPos >= headerTop) {
activeId = id;
}
});
if (activeId !== null) {
var newUrl = window.location.href.split('#')[0] + '#' + activeId;
window.history.pushState('', document.title, newUrl);
jQuery('.toc-link').removeClass('active'); // remove active class from all links
jQuery('.toc-link[data-id="' + activeId + '"]').addClass('active'); // add active class to matching link
}
});
});
您可以在此处查看此问题的实际情况。
我觉得这是一个简单的修复,但我的 JavaScript 不是很好。我将不胜感激任何指点。谢谢!
长话短说,问题似乎出在我滚动页面的方式上。尽管可能有更好的解决方案,但这就是我想出的方法 - 将
100
从 headerTop
变量中去掉:
var headerTop = jQuery(this).offset().top;
var headerTop = headerScrollTop - 100;