scrollTo.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. "use strict";
  2. var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
  3. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
  4. Object.defineProperty(exports, "__esModule", {
  5. value: true
  6. });
  7. exports.default = scrollTo;
  8. var _raf = _interopRequireDefault(require("rc-util/lib/raf"));
  9. var _easings = require("./easings");
  10. var _getScroll = _interopRequireWildcard(require("./getScroll"));
  11. function scrollTo(y, options = {}) {
  12. const {
  13. getContainer = () => window,
  14. callback,
  15. duration = 450
  16. } = options;
  17. const container = getContainer();
  18. const scrollTop = (0, _getScroll.default)(container);
  19. const startTime = Date.now();
  20. const frameFunc = () => {
  21. const timestamp = Date.now();
  22. const time = timestamp - startTime;
  23. const nextScrollTop = (0, _easings.easeInOutCubic)(time > duration ? duration : time, scrollTop, y, duration);
  24. if ((0, _getScroll.isWindow)(container)) {
  25. container.scrollTo(window.pageXOffset, nextScrollTop);
  26. } else if (container instanceof Document || container.constructor.name === 'HTMLDocument') {
  27. container.documentElement.scrollTop = nextScrollTop;
  28. } else {
  29. container.scrollTop = nextScrollTop;
  30. }
  31. if (time < duration) {
  32. (0, _raf.default)(frameFunc);
  33. } else if (typeof callback === 'function') {
  34. callback();
  35. }
  36. };
  37. (0, _raf.default)(frameFunc);
  38. }