2019-07-24 22:56:20 +08:00
|
|
|
import raf from 'raf';
|
2020-04-01 17:38:21 +08:00
|
|
|
import getScroll, { isWindow } from './getScroll';
|
2019-07-30 11:02:16 +08:00
|
|
|
import { easeInOutCubic } from './easings';
|
2019-07-24 22:56:20 +08:00
|
|
|
|
|
|
|
interface ScrollToOptions {
|
2019-07-24 23:56:20 +08:00
|
|
|
/** Scroll container, default as window */
|
2020-04-01 17:38:21 +08:00
|
|
|
getContainer?: () => HTMLElement | Window | Document;
|
2019-07-24 22:56:20 +08:00
|
|
|
/** Scroll end callback */
|
|
|
|
callback?: () => any;
|
|
|
|
/** Animation duration, default as 450 */
|
|
|
|
duration?: number;
|
|
|
|
}
|
|
|
|
|
2019-07-30 12:34:12 +08:00
|
|
|
export default function scrollTo(y: number, options: ScrollToOptions = {}) {
|
2019-07-30 11:02:16 +08:00
|
|
|
const { getContainer = () => window, callback, duration = 450 } = options;
|
2019-07-24 22:56:20 +08:00
|
|
|
|
|
|
|
const container = getContainer();
|
|
|
|
const scrollTop = getScroll(container, true);
|
|
|
|
const startTime = Date.now();
|
|
|
|
|
|
|
|
const frameFunc = () => {
|
|
|
|
const timestamp = Date.now();
|
|
|
|
const time = timestamp - startTime;
|
2019-07-30 11:02:16 +08:00
|
|
|
const nextScrollTop = easeInOutCubic(time > duration ? duration : time, scrollTop, y, duration);
|
2020-04-01 17:38:21 +08:00
|
|
|
if (isWindow(container)) {
|
|
|
|
(container as Window).scrollTo(window.pageXOffset, nextScrollTop);
|
|
|
|
} else if (container instanceof Document) {
|
|
|
|
container.documentElement.scrollTop = nextScrollTop;
|
2019-07-24 22:56:20 +08:00
|
|
|
} else {
|
|
|
|
(container as HTMLElement).scrollTop = nextScrollTop;
|
|
|
|
}
|
|
|
|
if (time < duration) {
|
|
|
|
raf(frameFunc);
|
2019-08-16 18:15:28 +08:00
|
|
|
} else if (typeof callback === 'function') {
|
|
|
|
callback();
|
2019-07-24 22:56:20 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
raf(frameFunc);
|
|
|
|
}
|