TIL 48 | 좌표구하기 1. Window sizes and scrolling

Gom·2021년 4월 7일
1

JavaScript

목록 보기
14/22
post-thumbnail

sticky 헤더를 자바스크립트로 구현해보기 위하여 현재 스크롤 상태 값을 가져오는 연습을 하고 있다. 이 과정에서 접하게된 브라우저 창의 너비/높이를 표현하는 방식과 스크롤을 제어하는 방법을 정리해두려 한다.

Width/height of the window

  1. window.innerWidth/innerHeight
  2. clientWidth/clientHeight (DOM 요소의 속성)

공통점 :

눈에 보이는 브라우저 창의 너비/높이를 알려준다. 메뉴와 툴 바는 제외된다.

차이점 :

window.innerWidth/innerHeight 스크롤바 포함

clientWidth/clientHeight 스크롤을 제외한 콘텐츠에 사용할 수있는 문서의 보이는 부분을 의미

사용방법 :

alert( window.innerWidth ); 
// full window width

alert( document.documentElement.clientWidth ); 
// window width minus the scrollbar

Read the current scroll

  1. window.pageXOffset/pageYOffset
  2. scrollLeft/scrollTop (DOM 요소의 속성)

차이점 :

window.pageXOffset/pageYOffset 요소의 위치 값

scrollLeft/scrollTop 브라우저 상단에서 현재 스크롤까지 스크롤이 이동한 값

사용방법 :

 const scrollTop =
      (document.documentElement &&
       document.documentElement.scrollTop) ||
      document.body.scrollTop;
//오래된 웹킷 기반 브라우저에서는
//document.body.scrollTop로 사용해야함.

alert('Current scroll from the top: ' 
      + window.pageYOffset);

alert('Current scroll from the left: ' 
      + window.pageXOffset);

기타

  • scrollLeft/scrollTop
    오래된 웹킷 기반 브라우저에서는 document.documentElement.scrollTop 대신 document.body.scrollTop으로 접근해야 한다.

  • window.pageXOffset/pageYOffset
    이 속성은 window.scrollX/scrollY와 같은 기능을 하지만 지원 범위에 차이가 있다. IE와 오래된 브라우저도 지원되는 pageOffset 사용을 권장 (단, IE9 미만은 두 속성 모두 지원 안됨)


Change the current scroll

  1. window.scrollTo(pageX,pageY)
    지정한 x, y 좌표로 이동
  2. window.scrollBy(x,y)
    현재 위치에서 x, y만큼 이동함.
  3. elem.scrollIntoView(top=true/false)
    해당하는 elem이 화면 상단/하단에 보여지도록 스크롤 이동.

참고자료
https://javascript.info/size-and-scroll-window#width-height-of-the-window
https://mommoo.tistory.com/85

profile
안 되는 이유보다 가능한 방법을 찾을래요

0개의 댓글