[React] 컴포넌트의 절대위치 찾기- window.scrollY, getBoundingClientRect 사용

bunny.log·2022년 10월 12일
0

절대위치

절대위치란? 해당 요소가 웹 페이지를 기준으로한 위치입니다!
스크롤된 컨텐츠의 길이 + Viewport 상대좌표를 구하면 요소의 절대위치를 구할 수 있습니다.

  • window.scrollY : 스크롤 양
  • Element.getBoundingClientRect() : 엘리먼트의 상대좌표를 알려주는 객체를 반환
const ele = document.getElementById(찾아야 하는 divElement 아이디);
const elePosition = window.scrollY + ele.getBoundingClientRect().top;

활용하기

	useEffect(() => {
		const watch = () => {
			window.addEventListener('scroll', getElementPostion);
		};
		watch();
		return () => {
			window.removeEventListener('scroll', getElementPostion);
		};
	});

	const getElementPostion = () => {
		const scrollY = window.scrollY;
		const available = document.getElementById('available');
		const unAvailable = document.getElementById('unAvailable');
		if (available && unAvailable) {
			const availablePosition = Math.floor(
				scrollY + available.getBoundingClientRect().top,
			);

			const unAvailablePosition = Math.floor(
				scrollY + unAvailable.getBoundingClientRect().top,
			);
		}
	};
profile
나를 위한 경험기록

0개의 댓글