https://jjyabbu.tistory.com/124
element.scrollIntoView
선택한 element가 있는 스크롤 영역에서 해당 element로 스크롤 시켜주는것임. 예를 들어 html과 css가 아래와 같이 되어있을 때 ... .overflow{ width:100px; height:200px; overflow:scroll; } .overflow section{ width:100px; h
jjyabbu.tistory.com
https://developer.mozilla.org/ko/docs/Web/API/Element/scrollIntoView
element.scrollIntoView - Web API | MDN
Element 인터페이스의 scrollIntoView() 메소드는 scrollIntoView()가 호출 된 요소가 사용자에게 표시되도록 요소의 상위 컨테이너를 스크롤합니다.
developer.mozilla.org
선택한 element가 있는 스크롤 영역에서 해당 element로 스크롤 시켜주는것임.
예를 들어 html과 css가 아래와 같이 되어있을 때
<div class="overflow">
<section></section>
<section></section>
<section></section>
<section class="hello"></section>
...
<section></section>
<section></section>
</div>
.overflow{
width:100px;
height:200px;
overflow:scroll;
}
.overflow section{
width:100px;
height:100px;
}
부모태그인 div의 height보다 모든 section의 height 총합이 더 커서 스크롤이 생길거임.
특정 행동을 취하면 class가 hello인 섹션이 보이도록 스크롤을 이동시킬 때 사용하는 게 scrollIntoView임.
자바스크립트에서 아래와 같은 함수를 이용해 사용할 수 있음.
const moveScroll = () => {
const hello = document.querySelector('.hello');
hello.scrollIntoView({ behavior: 'smooth', block: 'start' })
}
behavior:'smooth' 는 스크롤바가 부드럽게 움직이게 해줌
block은 'start', 'center', 'end', 'nearest'로 스크롤되는 위치를 조정해줄 수 있음.
근데 start, end 설정은 여백 없이 너무 딱 달라붙어서 실제로 보면 안이쁨.
이때 CSS로 scroll-margin 을 주면 된다.
.overflow{
width:100px;
height:200px;
overflow:scroll;
}
.overflow section{
width:100px;
height:100px;
scroll-margin:16px;
}
이러면 scrollIntoView 이벤트로 스크롤이 이동해도 상하 여백이 있어서 보기에 좋다.
if (e.key === 'ArrowDown') {
focused_ref.current?.parentElement?.nextElementSibling?.scrollIntoView(false);
setFocusedIndex(focused_index < searched_menus.length - 1 ? focused_index + 1 : focused_index);
}
if (e.key === 'ArrowUp') {
focused_ref.current?.parentElement?.previousElementSibling?.scrollIntoView(true);
setFocusedIndex(focused_index > 0 ? focused_index - 1 : focused_index);
}
'JavaScript' 카테고리의 다른 글
[자바스크립트] 디바운스란 뭘까? 간단한 사용 예제 (1) | 2025.03.06 |
---|---|
컴포넌트는 어떻게 등장하게 되었는가 (1) | 2024.10.18 |
[Javascript] 비동기, Promise, async, await (0) | 2024.10.08 |
[JS] 모달창 만들기, 자식 window에서 iframe 닫기, 데이터 전달하기 (0) | 2023.05.11 |
[JS] button태그에 onclick할 경우 location.href가 안되는 문제 (0) | 2023.05.09 |