본문 바로가기
언어/javascript

자바스크립트 브라우저 사이즈 변경시 가로, 세로 길이 값 가져오는 기능

by 클로드 2020. 12. 22.
반응형

브라우저 사이즈를 변경할때 resize 이벤트를 사용

 

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

window.addEventListener('resize', function() {
    console.log('resize');
});

 

스크롤 포함 가로 길이
window.innerWidth;

스크롤 포함 세로 길이
window.innerHeight;

스크롤 제외 가로 길이
document.documentElement.clientWidth;

스크롤 제외 세로 길이
document.documentElement.clientHeight;

 

예제 코드

<!doctype html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<style>
    html, body {
        margin: 0;
        padding: 0;
    }
    #app {
        height:2000px;
    }
</style>
<div id="app">
    <h1 id="innerWidth"></h1>
    <h1 id="innerHeight"></h1>
    <h1 id="clientWidth"></h1>
    <h1 id="clientHeight"></h1>
</div>
<script>
    (function() {
        function displaySize() {
            document.getElementById('innerWidth').innerHTML = 'innerWidth(스크롤 포함 가로길이) : ' + window.innerWidth;
            document.getElementById('innerHeight').innerHTML = 'innerHeight(스크롤 포함 세로길이) : ' + window.innerHeight;
            document.getElementById('clientWidth').innerHTML = 'clientWidth(스크롤 제외 가로길이) : ' + document.documentElement.clientWidth;
            document.getElementById('clientHeight').innerHTML = 'clientHeight(스크롤 제외 세로길이) : ' + document.documentElement.clientHeight;
        }

        displaySize();
        window.addEventListener('resize', displaySize);
    })();
</script>
</body>
</html>

 

예제 확인

wizd100.github.io/example/js-resize1

반응형

댓글