ant-design-vue/components/_util/scrollTo.ts

39 lines
1.3 KiB
TypeScript
Raw Normal View History

2021-05-11 14:42:14 +00:00
import raf from './raf';
import getScroll, { isWindow } from './getScroll';
2020-10-02 07:44:10 +00:00
import { easeInOutCubic } from './easings';
2020-10-13 14:26:56 +00:00
interface ScrollToOptions {
/** Scroll container, default as window */
2021-05-11 14:42:14 +00:00
getContainer?: () => HTMLElement | Window | Document;
2020-10-13 14:26:56 +00:00
/** Scroll end callback */
callback?: () => any;
/** Animation duration, default as 450 */
duration?: number;
}
2020-10-02 07:44:10 +00:00
2020-10-13 14:26:56 +00:00
export default function scrollTo(y: number, options: ScrollToOptions = {}) {
2020-10-02 07:44:10 +00: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;
const nextScrollTop = easeInOutCubic(time > duration ? duration : time, scrollTop, y, duration);
2021-05-11 14:42:14 +00:00
if (isWindow(container)) {
(container as Window).scrollTo(window.pageXOffset, nextScrollTop);
} else if (container instanceof HTMLDocument || container.constructor.name === 'HTMLDocument') {
(container as HTMLDocument).documentElement.scrollTop = nextScrollTop;
2020-10-02 07:44:10 +00:00
} else {
2020-10-13 14:26:56 +00:00
(container as HTMLElement).scrollTop = nextScrollTop;
2020-10-02 07:44:10 +00:00
}
if (time < duration) {
2021-05-11 14:42:14 +00:00
raf(frameFunc);
2020-10-02 07:44:10 +00:00
} else if (typeof callback === 'function') {
callback();
}
};
2021-05-11 14:42:14 +00:00
raf(frameFunc);
2020-10-02 07:44:10 +00:00
}