export function scrollToElementUnderline(elementId: string, duration: number = 375) {
const element = document.getElementById(elementId);
if (element) {
const rect = element.getBoundingClientRect();
const isVisible = rect.top >= 0 && rect.bottom <= window.innerHeight;
if (!isVisible) {
const startPosition = window.scrollY;
const endPosition = startPosition + rect.bottom - window.innerHeight;
const startTime = performance.now();
const animateScroll = (currentTime: number) => {
const elapsedTime = currentTime - startTime;
const progress = Math.min(elapsedTime / duration, 1);
const scrollPosition = startPosition + (endPosition - startPosition) * progress;
window.scrollTo(0, scrollPosition);
if (elapsedTime < duration) {
requestAnimationFrame(animateScroll);
}
};
requestAnimationFrame(animateScroll);
}
}
}
補足
idを指定するstring値を引数に取る
デフォルト引数のdurationはスクロールにかける時間(ms)を指定