【问题标题】:How can I add a heading’s anchor to the address bar as I scroll through it?如何在滚动浏览地址栏时将标题的锚点添加到地址栏?
【发布时间】:2020-09-18 21:02:34
【问题描述】:

我有一个很长的一页纸,里面有不同的部分,每个部分都在自己的<article id="section-title"> 中。我想以 Netlify 的文档 (see example) 的风格添加导航,它通过在滚动时附加当前部分的 id 来更改地址栏。我认为在第一部分之前滚动到顶部时返回原始 URL(没有锚点)会更好。不过,我不知道从哪里开始,也不知道如何寻找具有此功能的插件。

如何使用 jQuery 完成所有这些操作?

【问题讨论】:

  • “通过在滚动时附加当前部分的 id 来更改地址栏”我想不出任何理由这样做。你能详细说明吗?另请阅读有关锚链接的内容:riptutorial.com/html/example/1076/link-to-an-anchor
  • @ikiK 我有这么长的一页纸。因此,用户将通过在同一页面内滚动来查看所有文章。如果用户想要分享他们正在阅读的当前文章,他们将复制 URL,该 URL 已经具有该特定文章的锚点。查看我给出的示例中的行为(Netlify 的文档)。
  • @ikiK 我正在处理的页面类似于this one。看看所有内容都在同一页面上。

标签: jquery scroll hyperlink navigation anchor


【解决方案1】:

这个问题有点广泛,我很惊讶它没有关闭,但由于你是新来的,我会给你一个先机,你在这个网站上有你需要的一切:

你需要:

1- 查看您的文章是否在视口中并提取id。在这个主题上,你有几个不同的解决方案:Dynamically detect current div on page scroll in jQuery with random number of divs

2-您需要在不重新加载的情况下更新地址栏 URL,您需要了解如何在下一个主题上进行操作:Updating address bar with new URL without hash or reloading the pageHow do I modify the URL without reloading the page?

我已经给你做了一个基本的例子来说明它是如何工作的:

<html>

<body>
  <header>
    <style type="text/css">
      section {
        min-height: 300px
      }
    </style>
  </header>
  <section id="section1"> section 1</section>
  <section id="section2"> section 2</section>
  <section id="section3"> section 3</section>
  <section id="section4"> section 4</section>
  <script type="text/javascript">
    var isInViewport = function(elem) {
      var distance = elem.getBoundingClientRect();
      return (
        distance.top >= 0 &&
        distance.left >= 0 &&
        distance.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        distance.right <= (window.innerWidth || document.documentElement.clientWidth)
      );
    };

    var findMe = document.querySelectorAll('section');

    window.addEventListener('scroll', function(event) {
      // add event on scroll
      findMe.forEach(page => {
        //for each .page
        if (isInViewport(page)) {
          //if in Viewport
          console.clear();
          console.log(page.id);
          // exampla with hash #:
          //document.location.hash = page.id;

          //new url
          var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + page.id;
          window.history.pushState({
            path: newurl
          }, '', newurl);
        }
      });
    }, false);
  </script>
</body>

</html>

这足以让您自己动手了。首先在此处搜索主题以寻求答案,然后如果您卡在代码的某些部分上,请随时寻求帮助。

欢迎来到 SO,祝你好运。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    相关资源
    最近更新 更多