clientX,offsetX,pageX,screenX의 차이 (+ offsetHeight)

5/20에 정리한 내용에 재정리함


아래의 내용은 마우스 event의 객체로부터 얻는것이 가능하다

 const element = document.getElementById('myElement');

  element.addEventListener('mousemove', function(event) {
      console.log('clientX:', event.clientX);
      console.log('offsetX:', event.offsetX);
      console.log('pageX:', event.pageX);
      console.log('screenX:', event.screenX);
  });


1. clientX, clientY

  • 스크롤을 높이를 제외한 현재화면을 페이지를 기준으로 표시한다

  • 이미지의 빨간점이 x:0 y:0 기준


2. offsetX, offsetY

  • 요소를 기준으로 표시한다

  • 이미지의 빨간점이 x:0 y:0 기준



3. opageX, pageY

  • 스크롤을 높이를 포함한 현재화면을 페이지를 기준으로 표시한다

  • 이미지의 빨간점이 x:0 y:0 기준


4. screenX, screenY

  • 모니터를 기준으로 표시한다

  • 이미지의 빨간점이 x:0 y:0 기준

1



clientHeight / offsetHeight / scrollHeight 차이


clientHeight (요소내부)

box-sizing: content-box일때 : 요소 + padding 의 크기

box-sizing: border-box일때 : 요소 + padding + ScrollBar + border 의 크기


offsetHeight (요소외부)

요소 + padding + ScrollBar + border 의 크기


scrollHeight (요소를 초과하는 스크롤)

요소의 스크롤을 포함한 높이


예를들어 아래와 같은 경우는 아래와 같은 설명이 된다

스크롤의 높이(scrollHeight)가 해당 요소(offsetHeight)의 높이를 초과하는 경우

즉 요소에 스크롤이 존재하는가? 라는것을 확인하는 예제이다

element.scrollHeight > element.offsetHeight


화면에서 요소 위치제어 ( 2024/05/20 다시 정리 )

위치정보를 취득하는 방법은 크게 아래와 같다

- window객체를 이용시

- 이벤트 객체를 이용시 ( 위에서 설명한 부분 )

- 요소객체.getBoundingClientRect()를 이용시


1. window객체 이용시

window.innerWidth = 브라우저의 화면 넓이

window.innerHeight = 브라우저의 화면 높이

window.outerWidth = 브라우저의 전체의 화면 넓이

window.outerHeight = 브라우저의 전체의 화면 높이


eg


2.JS를 이용해서 요소에서 위치 취득법 요소객체.getBoundingClientRect()를 사용한다

- normal css의 right와 bottom을 구하는 방법이 다르다 (이미지 참조)

- normal css의 right와 bottom을 구하기 위해선 window.innerWidth - rect.righte등의 처리가 필요하다

위의 방법으로 구할시 normal Css의 right가 출력됨 ( 벤이 사용하는 방법 )

(상세한 설명은 잘 정리된 다른분의 이미지 자료를 첨부함)


const rect = element.getBoundingClientRect();
console.log('Top:', rect.top);
console.log('Right:', rect.right);
console.log('Bottom:', rect.bottom);
console.log('Left:', rect.left);
console.log('Width:', rect.width);
console.log('Height:', rect.height);


eg




참조

https://mong-blog.tistory.com/entry/clientX-offsetX-pageX-screenX-차이

https://stackoverflow.com/questions/21064101/understanding-offsetwidth-clientwidth-scrollwidth-and-height-respectively/21064102#21064102https://dev-chim.tistory.com/entry/Javascript-property-height-value

https://minsu092274.tistory.com/14

https://hianna.tistory.com/493

메인으로참고함

Mar 6, 2023 Views 116