Study/JavaScript

[JS] clientWidth & clientHeight

taecongs 2023. 7. 26. 15:21

알고있으면 좋은 Javascript Tip✨


clientWidth & clientHeight

  • JS에서 HTML 요소의 크기를 가져와서 계산하는 경우 사용되고 있다.
  • margin 값과 border 값이 제외된, padding 값까지만 적용된 내부의 실제 크기를 가져온다.
export default function isPoiAlarmCount(){
    let $iconList = document.querySelectorAll('.icon');
    let $poiContainer = document.querySelector("#poi-container");

    $iconList.forEach((data) => {
            const $selectIcon = e.target;
            const $selectId = Number($selectIcon.closest('.floor-row').dataset.floorId);
            const $selectCategory = $selectIcon.dataset.cate;
            const $selectAlarmCount = await allAPI.getPoiAlarmCountFunction($selectId, $selectCategory);

            const $alarmCount = document.querySelector('.poi-count');
            $alarmCount.innerText = $selectAlarmCount > 99 ? '99+' : $selectAlarmCount;

            // 클릭한 아이콘에 클래스를 추가한다.
            data.classList.add('active');

            // 알람박스의 위치를 설정한다.
            const $Height = $selectIcon.clientHeight;
            const $Width = $selectIcon.clientWidth;

            $poiContainer.style.top = $Height + 'px';
            $poiContainer.style.left = $Width / 2 + 'px';

            // 초기 값 display:none -> 아이콘 클릭 시 display:block
            $poiContainer.style.display = 'block';

            // 클릭된 아이콘의 위치를 기준으로 엘리먼트 추가한다.
            $selectIcon.append($poiContainer);
        });
    });

}
  • 현재 .icon 클래스에 style을 적용한 상태이다. (width:64;,  height:64;)
  • $Height, $Width 변수를 console.log로 확인해보면 둘 다 값이 64이다.
  • $Height + 'px'  === 64px 이다.
    $Width / 2 + 'px' === 32px 이다.

 

offsetWidth & offsetHeight

  • margin 값을 제외한 padding 값, border 값까지 계산한 값을 가져온다. (일반적으로 사용된다.)

'Study > JavaScript' 카테고리의 다른 글

[JS] contains & indexOf  (0) 2023.07.26
[JS] event.target  (0) 2023.07.26
[JS] sort  (0) 2023.07.21
[JS] find  (0) 2023.07.21
[JS] append & prepend & after & before  (0) 2023.07.21