简体   繁体   English

如何在“ scrollBehaviour:平稳”动画之后安排事件发生的时间?

[英]How can I time an event to happen after a 'scrollBehaviour: smooth' animation?

When ScrollToOptions.behavior is set to 'smooth', a supporting browser will smoothly scroll the page for you, but I am not sure what the timing of the animation is. ScrollToOptions.behavior设置为“ smooth”时, 支持的浏览器将为您平滑地滚动页面,但是我不确定动画的时间是多少。 I need to move focus after the animation (because doing it before will jump the scroll and cancel the animation). 我需要在动画之后移动焦点(因为这样做之前会跳过滚动并取消动画)。 If it's always a set duration I can just use that, but if it depends on the distance scrolled or changes from browser to browser, I might have to figure out something a little more fancy. 如果始终是一个设置的持续时间,我可以使用它,但是如果它取决于滚动的距离或浏览器之间的变化,则我可能不得不想一想。

In order to do this I might also need to figure out a way to check for ScrollToOptions support, though at least in Safari it just fails silently 为此,我可能还需要找出一种检查ScrollToOptions支持的方法,尽管至少在Safari中,它只是默默地失败了。

  if (options.smooth) {
    let scrollTiming = 250; // ?????

    window.scrollTo({
      top: element.offsetTop - fixedOverlay,
      behavior: 'smooth'
    });

    setTimeout(function() {
      element.focus();
    }, scrollTiming);
  } else {
    element.focus();
  }

Since window.scrollTo() emit scroll events just like when user scrolls, could you create a custom scrollend event by tracking when the regular scroll event stop being emitted? 由于window.scrollTo()就像用户滚动时一样会发出scroll事件,是否可以通过跟踪何时停止发出常规滚动事件来创建自定义的scrollend事件?

const removeScrollEndListener = (function() {
  let timer = null;
  const event = new Event('scrollend');

  const attachEvent = () => {
    clearTimeout(timer);
    timer = setTimeout(() => {window.dispatchEvent(event)}, 100)};

  window.addEventListener('scroll', attachEvent);

  return window.removeEventListener.bind(window, 'scroll', attachEvent);
})();

window.addEventListener('scrollend', () => {
  console.log(`scroll end, ${window.scrollY}`)
})

// later, remove custom event
removeScrollEndListener();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM