检查scrollTo完成

时间:2018-08-20 08:58:02

标签: javascript angularjs

我有一个可以滚动的元素。我还有一个滚动到特定位置的功能。当scrollTo完成时,我想调用一个函数。

Plunkr示例:http://plnkr.co/edit/ejDdIjC0DMjxcYXM3Xlx?p=preview

var x = document.querySelector('.container');
$scope.scrollTo = function() {
  x.scrollTo({
    top: 300 ,
    behavior: 'smooth'
  });
};

 // do something when scrollTo is finished

5 个答案:

答案 0 :(得分:1)

我修改了@DoiDor's answer以确保该位置是四舍五入的,并包括超时回退以防万一。否则,可能永远无法准确地达到这一位置,并且承诺也将永远无法解决。

async function scrollToPosition(container, position) {
  position = Math.round(position);

  if (container.scrollTop === position) {
    return;
  }

  let resolveFn;
  let scrollListener;
  let timeoutId;

  const promise = new Promise(resolve => {
    resolveFn = resolve;
  });

  const finished = () => {
    container.removeEventListener('scroll', scrollListener);
    resolveFn();
  };

  scrollListener = () => {
    clearTimeout(timeoutId);

    // scroll is finished when either the position has been reached, or 100ms have elapsed since the last scroll event
    if (container.scrollTop === position) {
      finished();
    } else {
      timeoutId = setTimeout(finished, 100);
    }
  };

  container.addEventListener('scroll', scrollListener);

  container.scrollTo({
    top: position,
    behavior: 'smooth',
  });

  return promise;
}

答案 1 :(得分:1)

我建议检查滚动运动是否消失。

参数少,无风险,适用于极端位置。

let position = null
const checkIfScrollIsStatic = setInterval(() => {
  if (position === window.scrollY) {
    clearInterval(checkIfScrollIsStatic)
    // do something
  }
  position = window.scrollY
}, 50)

答案 2 :(得分:0)

window.scrollTo()函数在完成时没有回调函数。您可以改用jquery.scrollTo函数。张贴示例:this

答案 3 :(得分:0)

通过检查要滚动到的元素的位置并将其与容器当前的滚动位置进行比较,您可以在滚动动作完成后看到该位置。

function isScrollToFinished() {
        const checkIfScrollToIsFinished = setInterval(() => {
            if (positionOfItem === scrollContainer.scrollTop) {
                // do something
                clearInterval(checkIfScrollToIsFinished);
            }
        }, 25);
}

时间间隔检查滚动容器的位置是否等于我要滚动到的元素的位置。然后采取措施并清除间隔。

答案 4 :(得分:0)

我正在使用与此类似的解决方案:

function scrollElementTo(el, position) {
  return new Promise((resolve) => {
    const scrollListener = (evt) => {
      if (typeof evt === 'undefined') {
        return;
      }

      const target = evt.currentTarget;

      if (target.scrollTop === position) {
        target.removeEventListener('scroll', scrollListener);
        resolve();
      }
    };

    el.addEventListener('scroll', scrollListener);

    // scroll to desired position (NB: this implementation works for
    // vertical scroll, but can easily be adjusted to horizontal 
    // scroll as well)
    el.scrollTo(0, position);
  });
}

const scrollContainer = document.querySelector('#theScrollContainer');

// desired y coords for scroll
const yDesiredScroll = 234;

scrollElementTo(scrollContainer, yDesiredScroll).then(() => {
    // do something here
});