본문 바로가기

JavaScript

[JS] 포커스 밀림 현상 해결, 스크롤 여백 scollIntoView

반응형

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);
}
반응형