mirror of
https://gitee.com/vant-contrib/vant.git
synced 2025-04-06 03:57:59 +08:00
58 lines
1.1 KiB
TypeScript
58 lines
1.1 KiB
TypeScript
import { raf, cancelRaf } from '@vant/use';
|
|
import { getScrollTop, setScrollTop } from '../utils';
|
|
|
|
let rafId: number;
|
|
|
|
export function scrollLeftTo(
|
|
scroller: HTMLElement,
|
|
to: number,
|
|
duration: number
|
|
) {
|
|
cancelRaf(rafId);
|
|
|
|
let count = 0;
|
|
const from = scroller.scrollLeft;
|
|
const frames = duration === 0 ? 1 : Math.round((duration * 1000) / 16);
|
|
|
|
function animate() {
|
|
scroller.scrollLeft += (to - from) / frames;
|
|
|
|
if (++count < frames) {
|
|
rafId = raf(animate);
|
|
}
|
|
}
|
|
|
|
animate();
|
|
}
|
|
|
|
export function scrollTopTo(
|
|
scroller: HTMLElement,
|
|
to: number,
|
|
duration: number,
|
|
callback: () => void
|
|
) {
|
|
let current = getScrollTop(scroller);
|
|
|
|
const isDown = current < to;
|
|
const frames = duration === 0 ? 1 : Math.round((duration * 1000) / 16);
|
|
const step = (to - current) / frames;
|
|
|
|
function animate() {
|
|
current += step;
|
|
|
|
if ((isDown && current > to) || (!isDown && current < to)) {
|
|
current = to;
|
|
}
|
|
|
|
setScrollTop(scroller, current);
|
|
|
|
if ((isDown && current < to) || (!isDown && current > to)) {
|
|
raf(animate);
|
|
} else if (callback) {
|
|
raf(callback as FrameRequestCallback);
|
|
}
|
|
}
|
|
|
|
animate();
|
|
}
|