为什么这个 jQuery 一页菜单在点击时选择了错误的项目?

问题描述 投票:0回答:2

我有一个奇怪的问题,当用户滚动或单击每个菜单项时,我使用 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 不是很好。我将不胜感激任何指点。谢谢!

jquery menu
2个回答
0
投票

我在控制台观察到

当点击标签时,你的数据ID对我来说很奇怪,如下所示:

activeId = '1-%D7%94%D7%9C%D7%94%D7%A7%D7%95%D7%AA-%D7%91%D7%A7%D7%95%D7%9E%D7% 93%D7%99%D7%94-%D7%93%D7%9C%D7%B3%D7%90%D7%A8%D7%98%D7%94'

您可以检查您的 active-Id 因为您已在该属性中传递了数字 ID。


0
投票

长话短说,问题似乎出在我滚动页面的方式上。尽管可能有更好的解决方案,但这就是我想出的方法 - 将

100
headerTop
变量中去掉:

    var headerTop = jQuery(this).offset().top;
    var headerTop = headerScrollTop - 100;
© www.soinside.com 2019 - 2024. All rights reserved.