ant-design/components/_util/scrollTo.ts

38 lines
1.1 KiB
TypeScript
Raw Normal View History

import raf from 'raf';
import getScroll from './getScroll';
2019-07-30 11:02:16 +08:00
import { easeInOutCubic } from './easings';
interface ScrollToOptions {
2019-07-24 23:56:20 +08:00
/** Scroll container, default as window */
getContainer?: () => HTMLElement | Window;
/** 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;
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);
if (container === window) {
2019-07-30 12:34:12 +08:00
window.scrollTo(window.pageXOffset, nextScrollTop);
} 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();
}
};
raf(frameFunc);
}