컴포넌트 절대위치 찾기

웹 페이지를 만들다 보면 해당 요소의 절대위치를 찾아야 할 때 있습니다,
절대위치를 이용해 스타일을 꾸미거나 로직을 만들때 사용할 수 있습니다.



절대위치

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

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


활용하기

스크롤을 할 때 마다 절대위치를 구하는 방법
header, main, footer의 id값을 가진 엘리먼트의 절대위치를 구해보겠습니다.


const [position, setPostion] = useState({
	header:false,
  	main:false,
  	footer:false,
});

const getElementPostion = () => {
	const header = document.getElmentById('header');
  	const main = document.getElmentById('main');
  	const footer = document.getElmentById('footer');
  	const scrollY = window.scrollY; // 스크롤 양
  
  	const headerPosition = Math.floor(scrollY + header.getBoundingClientRect().top); // 절대위치, Math.floor로 정수로 변환
    const mainPosition = Math.floor(scrollY + main.getBoundingClientRect().top);
    const fooerPosition = Math.floor(scrollY + footer.getBoundingClientRect().top);
  
  	setPosition({
    	header: scrollY >= headerPosition && 
		        scrollY < mainPosition, // 스크롤양이 헤더영역보다 많고 메인영역 전
    	main: scrollY >= mainPosition &&
      		  scrollY < fooerPosition, //스크롤양이 메인보다 많고 푸터보다 적을 때
    	footer: scrollY >= fooerPosition, //스크롤양이 푸터보다 많을때
    })
}

useEffect(()=>{
  window.addEventListener('scroll', getBannerPosition); // 스크롤시 getBannerPosition 발생
  
  return () =>   window.removeEventListener('scroll', getBannerPosition); // 클린업, 페이지를 나가면 이벤트 삭제
},[position]) // position 값이 변할 때마다 effect 실행

절대위치를 활용하면 뷰포트가 사용자에게 보일때 스타일을 강조할 수 있습니다.

profile
Junior Front-End Developer 👨‍💻

0개의 댓글