lx-admin-frontend/src/utils/scroll-to.ts

66 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-04-02 01:01:56 +08:00
const easeInOutQuad = (t: number, b: number, c: number, d: number) => {
2023-04-03 00:05:09 +08:00
t /= d / 2;
if (t < 1) {
return (c / 2) * t * t + b;
}
t--;
return (-c / 2) * (t * (t - 2) - 1) + b;
2023-04-02 01:01:56 +08:00
};
// requestAnimationFrame for Smart Animating http://goo.gl/sx5sts
const requestAnimFrame = (function () {
2023-04-03 00:05:09 +08:00
return (
window.requestAnimationFrame ||
(window as any).webkitRequestAnimationFrame ||
(window as any).mozRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
}
);
2023-04-02 01:01:56 +08:00
})();
/**
* Because it's so fucking difficult to detect the scrolling element, just move them all
* @param {number} amount
*/
const move = (amount: number) => {
2023-04-03 00:05:09 +08:00
document.documentElement.scrollTop = amount;
(document.body.parentNode as HTMLElement).scrollTop = amount;
document.body.scrollTop = amount;
2023-04-02 01:01:56 +08:00
};
const position = () => {
2023-04-03 00:05:09 +08:00
return document.documentElement.scrollTop || (document.body.parentNode as HTMLElement).scrollTop || document.body.scrollTop;
2023-04-02 01:01:56 +08:00
};
/**
* @param {number} to
* @param {number} duration
* @param {Function} callback
*/
export const scrollTo = (to: number, duration: number, callback?: any) => {
2023-04-03 00:05:09 +08:00
const start = position();
const change = to - start;
const increment = 20;
let currentTime = 0;
duration = typeof duration === 'undefined' ? 500 : duration;
const animateScroll = function () {
// increment the time
currentTime += increment;
// find the value with the quadratic in-out easing function
const val = easeInOutQuad(currentTime, start, change, duration);
// move the document.body
move(val);
// do the animation unless its over
if (currentTime < duration) {
requestAnimFrame(animateScroll);
} else {
if (callback && typeof callback === 'function') {
// the animation is done so lets callback
callback();
}
}
};
animateScroll();
2023-04-02 01:01:56 +08:00
};