【TypeScript】JQueryを使わずページをヌルっとスクロールさせる
2022-1-12 | TypeScript
JQueryを使わず、且つ、TypeScriptを使ってページをヌルっとスクロールさせたい!
手順書
実際のコードを下記に示す。
class Scroll {
constructor() {
const duration: number = 500;
window.addEventListener("DOMContentLoaded", () => {
const scrollTriggers: HTMLElement[] = [].slice.call(document.querySelectorAll('a[href^="#"]'));
scrollTriggers.forEach((scrollTrigger) => {
scrollTrigger.addEventListener("click", (e) => {
const href: string = scrollTrigger.getAttribute("href") as string;
if (href) {
const currentPosition: number = document.documentElement.scrollTop || document.body.scrollTop;
const targetElement: HTMLElement = document.getElementById(href.replace("#", "")) as HTMLElement;
if (targetElement) {
e.preventDefault();
e.stopPropagation();
const targetPosition: number = window.pageYOffset + targetElement.getBoundingClientRect().top;
const startTime: number = performance.now();
const loop = (nowTime: number) => {
const time: number = nowTime - startTime;
const normalizedTime: number = time / duration;
if (normalizedTime < 1) {
window.scrollTo(0, currentPosition + ((targetPosition - currentPosition) * this.easeInOut(normalizedTime)));
requestAnimationFrame(loop);
} else {
window.scrollTo(0, targetPosition);
}
};
requestAnimationFrame(loop);
}
}
});
});
});
}
easeInOut(t: number) {
return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
}
}
const scroll = new Scroll();
感想文(まとめ)
何でもかんでもTypeScriptにしたい。