[Javascript] clientWidth, clientHeight / scrollWidth, scrollHeight / scrollTop , scrollLeft
clientWidth / clientHeight
border 안의 사이즈 값
요소의 너비와 패딩을 포함한 값 (*스크롤바의 너비는 포함하지 않는다)
<style>
#example {
width: 300px;
height: 200px;
margin:20px;
padding:25px;
border: 10px solid black;
background-color: tomato;
}
</style>
<div id="example"></div>
<script>
const example = document.getElementById("example");
console.log(example.clientWidth); // 350
console.log(example.clientHeight); // 250
</script>
clientWidth : 기본 width(300px) + 양 쪽 padding (25px + 25px) = 350
clientHeight : 기본 height(200px) + 위 아래 padding (25px + 25px) = 250
스크롤을 추가해보자.
<style>
#example {
width: 300px;
height: 200px;
margin:20px;
padding:25px;
border: 10px solid black;
background-color: tomato;
overflow:auto;
}
</style>
<div id="example">
//생략
</div>
<script>
const example = document.getElementById("example");
console.log(example.clientWidth); // 333
console.log(example.clientHeight); // 250
</script>
<script src="./test.js"></script>
스크롤이 없었을 땐 clientWidth 가 350였지만
스크롤이 추가 되니 콘텐츠의 영역에 스크롤바가 할당되어
333으로 줄어든 것을 볼 수 있다.
*스크롤바의 너비는 브라우저마다 다르다
scrollWidth / scrollHeight
clientWidth와 clientHeight과 비슷하지만 스크롤바에 가려진
요소의 영역도 포함되는 점이 다르다.
<style>
#example {
width: 300px;
height: 200px;
padding: 25px;
margin:20px;
border: 10px solid black;
background-color: tomato;
overflow: auto;
}
</style>
<div id="example">
//생략
</div>
<script>
const example = document.getElementById("example");
console.log(example.scrollWidth); // 333
console.log(example.scrollHeight); // 302
</script>
<script src="./test.js"></script>
scrollWidth : border안쪽의 가로너비(350px) - 스크롤바의 너비(17px) = 333
scrollHeight : border안쪽의 세로너비(250px) + 스크롤로 가려진 영역 = 302
overflow: hidden으로 스크롤바를 안보이게 한다면?
scrollWidth : border안쪽의 가로너비(350px) - 스크롤바의 너비(0) = 350
scrollHeight : border안쪽의 세로너비(250px) + 스크롤로 가려진 영역 = 302
스크롤 바로 인해 줄어들었던 width는 원래의 콘텐츠값으로 변경되고
height는 가려진 영역의 값을 그대로 포함하고 있는것을 확인할 수 있다.
scrollLeft / scrollTop
스크롤의 움직임에 따라 가려진 영역의 너비와 높이의 값을 구해준다.
#example {
width: 300px;
height: 200px;
padding: 25px;
margin:20px;
border: 10px solid black;
background-color: tomato;
overflow: auto;
}
</style>
<div id="example">
//생략
</div>
<script>
const example = document.getElementById("example");
function handleScroll(){
console.log(example.scrollTop);
}
example.addEventListener("scroll", handleScroll);
console.log(example.scrollWidth); // 333
console.log(example.scrollHeight); // 302
</script>
스크롤시에 scrollTop의 값을 console에 보여지게끔 코드를 작성했다.
현재 scrollHeight는 302이며 원래 콘텐츠의 영역은 250이였으니 가려진 영역은 52로 볼 수 있다.
해당 example에서 스크롤을 하면 0에서 부터 맨 밑까지 스크롤시 scrollTop이 52까지 올라가는것으로 확인된다.
즉 스크롤을 밑으로 내리면 영역이 위로 올라감으로써 위쪽의 영역이 가려지게되는데 이 값이 scrollTop이다.
scrollLeft도 같은 방식으로 적용된다.
그러면 위의 정보들로 구할수 있는 값은 무엇이 있을까?
scrollTop의 정보는 구할 수 있지만 하단 기준으로 얼마나 스크롤이 되었는지 확인하려면?
let bottom = example.scrollHeight - example.clientHeight - example.scrollTop;
위와 같이 값을 구할 수 있다.