JavaScript

[JavaScript] 특정 요소에 따른 스크롤 자동 조정 : scrollIntoView()

hid1 2023. 1. 3. 22:49

element.scrollIntoView

scrollIntoView()를 호출하면 호출된 요소가 사용자에게 보여지도록 상위 요소의 스크롤이 이동된다.

 

element.scrollIntoView();
element.scrollIntoView(alignToTop); // Boolean 파라미터
element.scrollIntoView(scrollIntoViewOptions); // Object 파라미터

alignTop

true : 상단을 기준으로 스크롤

 - scrollIntoViewOptions: {block: "start", inline: "nearest"}와 동일하다.

false : 하단을 기준으로 스크롤

 - scrollIntoViewOptions: {block: "end", inline: "nearest"}와 동일하다.

scrollIntoViewOptions

behavior : 스크롤 애니에미션에 대한 정의

- auto (default)

- smooth 

block : 수직 정렬

- start (default)

- center

- end

- nearest

inline: 수평 정렬

- start 

- center

- end

nearest (default)

 

 

적용

 

 

검색 자동완성으로 키보드 아래방향 키를 누르면 아래로 하나씩 포커스되며 그 요소를 기준으로 스크롤하는 기능을 구현하였다. 

 

const scrollRef = useRef(null);
useEffect(() => {
 scrollRef.current.scrollIntoView({ behavior: "smooth", block: "center" });
}, [focusIndex]);

 

리액트를 사용하고 있어 useRef를 통해 요소를 가져왔다. 지금 포커스된 요소를 알려주는 focusIndex 상태가 바뀔 때마다 scrollIntoView 함수를 호출하였다. 애니메이션 효과를 주기위해 behavior: "smooth", 요소가 상위 컨테이너 기준으로 세로 가운데로 정렬할 수 있게  block: "center" 옵션을 주었다.

 

const SearchResultItem = ({ isFocus, scrollRef }) => {
  return (
    <Base ref={isFocus ? scrollRef : undefined}>
		// 생략
    </Base>
  );
};

 

isFocus 상태를 통해 지금 요소가 포커스되어 있는 상태일 때 ref에 scrollRef를 지정해주었다.

 

 

 

 

반응형