scrollTo.js 1.0 KB

12345678910111213141516171819202122232425262728293031
  1. import raf from "rc-util/es/raf";
  2. import { easeInOutCubic } from './easings';
  3. import getScroll, { isWindow } from './getScroll';
  4. export default function scrollTo(y, options = {}) {
  5. const {
  6. getContainer = () => window,
  7. callback,
  8. duration = 450
  9. } = options;
  10. const container = getContainer();
  11. const scrollTop = getScroll(container);
  12. const startTime = Date.now();
  13. const frameFunc = () => {
  14. const timestamp = Date.now();
  15. const time = timestamp - startTime;
  16. const nextScrollTop = easeInOutCubic(time > duration ? duration : time, scrollTop, y, duration);
  17. if (isWindow(container)) {
  18. container.scrollTo(window.pageXOffset, nextScrollTop);
  19. } else if (container instanceof Document || container.constructor.name === 'HTMLDocument') {
  20. container.documentElement.scrollTop = nextScrollTop;
  21. } else {
  22. container.scrollTop = nextScrollTop;
  23. }
  24. if (time < duration) {
  25. raf(frameFunc);
  26. } else if (typeof callback === 'function') {
  27. callback();
  28. }
  29. };
  30. raf(frameFunc);
  31. }