JS : 스크롤 동적처리 2. pageYOffset, getBoundingClientRect

 

 

 

window.pageYOffset

* 웹 문서가 수직으로 얼마나 스크롤됐는지 px 단위로 반환하는 속성입니다.

* window scroll 이벤트와 함께 실시간으로 스크롤 진행 여부를 체크하는 용도로 많이 사용합니다.

* 가로 스크롤 위치 확인 시 pageXOffset 속성을 사용합니다.(사용방법 동일)

* 사용 전 충분한 세로 스크롤이 필요합니다.

* 동일 의미를 가지는 속성으로 scrollY 가 있습니다.

PageYOffset scrollY
scrollY

 

 

▼ 적용예시(window scroll 이벤트 활용)

<p id="result"></p>
const result = document.querySelector('#result')
window.addEventListener('scroll',function(){ //스크롤 할 경우 
	result.innerHTML = window.pageYOffset //현재 스크롤 위치값을 반환합니다.
})

See the Pen JS-pageYOffset by yuna122212 (@yuna122212) on CodePen.

 

▼ 적용예시(window scroll 이벤트 + if 조건문 활용)

window.addEventListener('scroll',function(){
  if(window.pageYOffset > 200){
      console.log('현재 스크롤 Y 위치가 200px보다 크다')
  }else{
      console.log('현재 스크롤 Y 위치가 200px보다 작다')
  }
})

See the Pen JS-pageYOffset-2 by yuna122212 (@yuna122212) on CodePen.

 

 


 

DOM.getBoundingClientRect()

DOM.getBoundingClientRect().속성

요소의 위치를 뷰포트 기준으로 상대적인 위치값으로 반환해주는 메서드입니다.

▼ 이미지 기준으로 pageX,Y는 pageYOffset 기준 좌표이며,

    clientX, Y는 getBoundingClientRect().top 기준 좌표입니다.

이미지 출처&nbsp;https://javascript.info/coordinates

 

 

▼ 적용예시 offsetTop & getBoundingClientRect() 비교

 

1. #result 대상에 left, top 좌표와 width, height 크기를 준비합니다.

<p id="result">RESULT</p>
#result {
  position:relative; left:20px; top:100px;
  width:200px; height:100px;
}

 

2. offsetTop과 getBoundingClientRect() 작성 시 스크롤 위치에 따라 다른 결과를 확인하세요.

이미지출처&nbsp;https://javascript.info/coordinates

const result = document.querySelector('#result')
console.log(result.offsetTop) //웹브라우저 최상단 기준 고정값 확인
console.log(result.getBoundingClientRect()) //뷰포트 기준 상대값 확인

//속성을 추가하여 원하는 속성만 골라 작성할 수도 있습니다!
console.log(result.getBoundingClientRect().bottom)
console.log(result.getBoundingClientRect().height)
console.log(result.getBoundingClientRect().left)
console.log(result.getBoundingClientRect().right)
console.log(result.getBoundingClientRect().top)
console.log(result.getBoundingClientRect().x)
console.log(result.getBoundingClientRect().y)

 

 

▼ 적용예시 getBoundingClientRect()  +  if조건문 활용

* 주의! 아래 명령에 따라 테스트 결과 체크 시

offsetTop 위치값을 스크롤 이벤트 외부에서 먼저 확인 후 그보다 1px이라도 큰 값을 조건에 작성해야합니다.

ex) offsetTop이 200인 경우 조건문에 201부터 조건으로 입력합니다. * 단위는 픽셀로 적용됩니다.

window.addEventListener('scroll',function(){

  console.log(`top>> ${result.offsetTop}`)
  if(result.offsetTop < 100){
  	console.log('offset 100보다 크다')
  }

  console.log(`top>> ${result.getBoundingClientRect().top}`)
  if(result.getBoundingClientRect().top < 100){
  	console.log('100보다 크다')
  }

})

See the Pen JS-getBoundingClientRect by yuna122212 (@yuna122212) on CodePen.

 

See the Pen JS-getBoundingClientRect-2 by yuna122212 (@yuna122212) on CodePen.

 

  Comments,     Trackbacks