문제 발생
메뉴 클릭 시 , 해당 화면으로 스크롤 이동하는 기능을 만들고 있는데, 메뉴를 처음 클릭 시에는 알맞는 화면으로 이동하는데, 다시 클릭하면 처음 메뉴 화면으로 이동한다. (참고로 메뉴 바는 상단에 고정되어 있다)
해당 화면으로 스크롤 이동 기능
처음에는 메뉴 클릭시, 해당 화면으로 이동할 수 있게 스크롤 기능을 구현하였다. 해당 tab에 대한 내용을 id로 설정했고 그 id에 맞는 화면으로 부드럽게 이동하려고 로직을 구현하였다. 하지만 위에 처럼 해당 문제가 발생하였다.
const movetToContent = (tab: string) => {
const target = document.getElementById(tab)?.offsetTop ?? 0;
const headerHeight = document.getElementById('Header')?.offsetHeight ?? 0;
const currentScroll = window.scrollY;
const targetScroll = target - headerHeight - 100;
window.scrollTo({
top: targetScroll,
behavior: 'smooth',
});}
원인을 분석해보니, currentScroll이 targetScroll과 다른 현상이 발생한 모습을 확인할 수 있었다. currentScroll같은 경우는 targetScroll보다 업데이트가 늦는 현상이 발견되었다.
계속 클릭 해도, 해당 화면으로 이동 할 수 있게 로직 구현
window.requestAnimationFrame()메서드를 사용해서 리페인트 바로 전에 실행할 수 있게 하였다.
더보기
requestAnimationFrame이란?
브라우저에게 수행하기를 원하는 애니메이션을 알리고 다음 리페인트 바로 전에 브라우저가 해당 함수를 호출 요청하는 메서드라고 할 수 있습니다.
requestAnimationFrame(() => {
const target = document.getElementById(tab)?.offsetTop ?? 0;
const headerHeight = document.getElementById('Header')?.offsetHeight ?? 0;
const currentScroll = window.scrollY;
const targetScroll = target - headerHeight - 100;
window.scrollTo({
top: targetScroll,
behavior: 'smooth',
});});
'개발 공부 > Vue' 카테고리의 다른 글
AOS 뒤로가기 버튼 클릭시, 해당 모달 닫히게 설정 (1) | 2024.11.16 |
---|---|
[Vue]공통 컴포넌트로 내용이 다른 게시물로 이동시, 해당 내용이 안 보여지는 현상 (0) | 2024.08.26 |
[Vue] v-html을 사용하면 안된다…?( vue-dompurify-html 변경, XSS공격) (0) | 2024.08.02 |
chart.js 그래프 다시 그리기(그래프 초기화) (0) | 2024.06.17 |