【问题标题】:How do I offset the anchor scroll that overlaps elements?如何偏移与元素重叠的锚滚动?
【发布时间】:2020-06-24 22:42:14
【问题描述】:

如何向元素哈希位置添加偏移量,以便窗口顶部的导航栏不会与我的内容重叠?

<nav id="nav">
  <a href="#home">Home</a>
  <a href="#about">About</a>
  <a href="#contact">Contact</a>
</nav>

<main>
  <section id="home">
    <h2>Welcome to example.com</h2>
  </section>
  <section id="about">
    <h1>About us</h1>
  </section>
  <section id="contact">
    <h2>Contact us</h2>
  </section>
</main>

我在互联网上找到的最简单的解决方案是在目标元素 section{ margin-top:100px } 中添加一些 margin-toppadding-top,但这会干扰我的设计,我不想使用隐藏元素进行破解来解决这个问题。

【问题讨论】:

    标签: anchor offset hashchange


    【解决方案1】:

    TL;DR

    window.addEventListener("hashchange", function(e){
      e.preventDefault()
      const navHeight = document.getElementById("nav").offsetHeight
      const target = document.getElementById(window.location.hash.substring(1))
      window.scrollTo(0, target.offsetTop - navHeight)
    })
    

    很遗憾,我不知道这个问题的 jQuery 解决方案。

    说明

    那么这是如何工作的,我们向正在寻找哈希变化的窗口添加一个事件监听器。 我们希望阻止默认浏览器滚动并使用我们自己的“调整后”滚动偏移。

    如果您的页面顶部有一个始终显示的粘性导航,我们需要知道导航元素的高度。 const navHeight = doc.getElementById("nav").offsetHeight

    接下来我们获取哈希位置,对于example.com/about.html#team,我们想要获取不带哈希符号window.location.hash.substring(1) 的哈希位置,返回"team"

    现在我们需要通过将返回的哈希位置传递给将返回目标元素的 document.getElementById(window.location.hash.substring(1))` 来获取目标元素。

    现在我们做一些简单的数学运算来偏移导航元素,这样它就不会与您有价值的内容重叠。
    target.offsetTop - navHeight

    作为最后一步,我们将新计算的偏移量传递给窗口滚动函数。
    window.scrollTo(0, target.offsetTop - navHeight)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-24
      • 2022-01-02
      • 2018-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多