scrollTo.js 1.0 KB

1234567891011121314151617181920212223242526272829303132
  1. import raf from './raf';
  2. import { easeInOutCubic } from './easings';
  3. import getScroll, { isWindow } from './getScroll';
  4. export default function scrollTo(y) {
  5. let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  6. const {
  7. getContainer = () => window,
  8. callback,
  9. duration = 450
  10. } = options;
  11. const container = getContainer();
  12. const scrollTop = getScroll(container, true);
  13. const startTime = Date.now();
  14. const frameFunc = () => {
  15. const timestamp = Date.now();
  16. const time = timestamp - startTime;
  17. const nextScrollTop = easeInOutCubic(time > duration ? duration : time, scrollTop, y, duration);
  18. if (isWindow(container)) {
  19. container.scrollTo(window.scrollX, nextScrollTop);
  20. } else if (container instanceof Document) {
  21. container.documentElement.scrollTop = nextScrollTop;
  22. } else {
  23. container.scrollTop = nextScrollTop;
  24. }
  25. if (time < duration) {
  26. raf(frameFunc);
  27. } else if (typeof callback === 'function') {
  28. callback();
  29. }
  30. };
  31. raf(frameFunc);
  32. }