📌 scrollIntoView
element.scrollIntoView(alignToTop, {scrollIntoViewOptions});
: 호출 된 요소가 화면에 보이도록 스크롤
⏩ alignToTop: boolean 값
- true: 요소의 상단으로 스크롤
- `scrollIntoViewOptions: {block: "start", inline: "nearest"}`와 일치
- 기본 값
- false: 요소의 하단으로 스크롤
- `scrollIntoViewOptions: {block: "end", inline: "nearest"}`와 일치
⏩ scrollIntoViewOptions: 속성을 포함하는 객체
- behavior: 애니메이션 적용
- "auto": 스크롤이 계산된 값에 의해 결정
- "smooth": 부드럽게 애니메이션을 적용하여 스크롤
- "instant": 스크롤 즉시 적용
- block: 수직 정렬
- "start": 요소를 뷰포트의 시작 부분에 정렬
- "center": 요소를 뷰포트의 중앙에 정렬
- "end": 요소를 뷰포트의 끝 부분에 정렬
- "nearest": 요소를 현재 스크롤 위치와 가장 가까운 위치에 정렬
- inline: 수평 정렬
- "start": 요소를 수평적으로 뷰포트의 시작 부분에 정렬
- "center": 요소를 수평적으로 뷰포트의 중앙에 정렬
- "end": 요소를 수평적으로 뷰포트의 끝 부분에 정렬
- "nearest": 요소를 현재 수평 스크롤 위치와 가장 가까운 위치에 정렬
element.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });
예제
function ScrollUpAndDown() {
const handleScrollDown = () => {
const targetElement = document.querySelector('.buttonGroup');
targetElement.scrollIntoView({ block: 'start', behavior: 'smooth' });
};
const handleScrollUp = () => {
const targetElement = document.querySelector('.NavContents');
targetElement.scrollIntoView({ block: 'end', behavior: 'smooth' });
};
return (
<div role="group" className="buttonGroup">
<button
type="button"
className="scrollDown"
aria-label="스크롤 다운"
title="스크롤 다운"
onClick={handleScrollDown}
>
<svg
fill="currentColor"
strokeWidth={0}
viewBox="0 0 512 512"
height="1em"
width="1em"
>
<path
d="m112 268 144 144 144-144M256 392V100"
fill="none"
stroke="currentColor"
strokeLinecap="square"
strokeMiterlimit={10}
strokeWidth="48px"
/>
</svg>
</button>
<button
type="button"
className="scrollUp"
aria-label="스크롤 업"
title="스크롤 업"
onClick={handleScrollUp}
>
<svg
fill="currentColor"
strokeWidth={0}
viewBox="0 0 512 512"
height="1em"
width="1em"
>
<path
d="m112 268 144 144 144-144M256 392V100"
fill="none"
stroke="currentColor"
strokeLinecap="square"
strokeMiterlimit={10}
strokeWidth="48px"
/>
</svg>
</button>
</div>
);
}
export default ScrollUpAndDown;