如何检测自动滚动到锚点?

Tam*_*ári 5 javascript anchor dom-events hashchange

我有一个单页网站example.com。有两个部分:页面顶部的介绍和页面底部的联系人。如果我想让某人访问联系部分而不必滚动介绍,我给他们这个链接:example.com/#contact。我在下面谈论这些访问。

浏览器会自动向下滚动到接触部分,但它忽略页面顶部的固定导航,所以接触部分的导航背后滚动,因此顶部接触部分变得不可见。这就是我想使用 JavaScript 通过从滚动位置减去固定导航的高度来纠正的。我们将此函数称为scrollCorrector. 问题是我不确切知道这种自动滚动何时发生,所以scrollCorrector每次都应该调用它。

什么时候应该scrollCorrector调用?由于散列部分而发生自动滚动时。为什么不使用onscroll?因为这样我无法区分自动滚动和用户滚动。为什么不在 eachonclick上使用<a href="example.com/#contact">?我会使用它,但是如果用户通过浏览器的后退按钮导航怎么办?好的,我也会用onpopstate。但是,如果用户来自example.com/#intro通过手动将 URL 重写为example.com/#contact怎么办?好的,我也会用onhashchange。但是如果用户已经在example.com/#contact 上,点击地址栏,然后按回车键而不做任何修改怎么办?以上都没有帮助。

那我应该听什么事件?如果这样的事件不存在,怎么scrollCorrector知道自动滚动刚刚发生?

Kai*_*ido 4

滚动事件将会触发,所以你可以,

  • 检查您的实际情况location.hash,如果为空我们不在乎
  • 对事件进行反跳,以确保不是鼠标滚轮触发了它
  • 获取实际的document.querySelector(location.hash).getBoundingClientRect().top,如果是,===0则致电您的scrollCorrector.

var AnchorScroller = function() {
  // a variable to keep track of last scroll event
  var last = -100, // we set it to -100 for the first call (on page load) be understood as an anchor call
    // a variable to keep our debounce timeout so that we can cancel it further
    timeout;

  this.debounce = function(e) {
    // first check if we've got a hash set, then if the last call to scroll was made more than 100ms ago
    if (location.hash !== '' && performance.now() - last > 100)
    // if so, set a timeout to be sure there is no other scroll coming
      timeout = setTimeout(shouldFire, 100);
    // that's not an anchor scroll, stop it right now !	
    else clearTimeout(timeout);
    // set the new timestamp
    last = performance.now();
  }

  function shouldFire() {
    // a pointer to our anchored element
    var el = document.querySelector(window.location.hash);
    // if non-null (an other usage of the location.hash) and that it is at top of our viewport
    if (el && el.getBoundingClientRect().top === 0) {
      // it is an anchor scroll
      window.scrollTo(0, window.pageYOffset - 64);
    }
  }
};
window.onscroll = new AnchorScroller().debounce;
Run Code Online (Sandbox Code Playgroud)
body {
  margin: 64px 0 0 0;
}
nav {
  background: blue;
  opacity: 0.7;
  position: fixed;
  top: 0;
  width: 100%;
}
a {
  color: #fff;
  float: left;
  font-size: 30px;
  height: 64px;
  line-height: 64px;
  text-align: center;
  text-decoration: none;
  width: 50%;
}
div {
  background: grey;
  border-top: 5px #0f0 dashed;
  font-size: 30px;
  padding: 25vh 0;
  text-align: center;
}
#intro,#contact {  background: red;}
Run Code Online (Sandbox Code Playgroud)
<nav>
  <a href="#intro">Intro</a>
  <a href="#contact">Contact</a>
</nav>
<div id="intro">  Intro </div>
<div> Lorem </div>
<div id="contact">  Contact </div>
<div> Ipsum </div>
Run Code Online (Sandbox Code Playgroud)

注意事项:
- 它在滚动事件和更正之间引入了 100 毫秒的超时,这是可见的。
- 它不是 100% 防弹的,用户只能触发一个事件(通过鼠标滚轮或键盘)并恰好落在正确的位置,因此会产生误报。但这种情况发生的可能性很小,因此这种行为可能是可以接受的。