jquery를 사용하여 스크롤바없이 브라우저 뷰포트의 높이와 너비를 얻습니까?


97

jQuery를 사용하여 스크롤바없이 브라우저 뷰포트의 높이와 너비를 어떻게 얻습니까?

지금까지 시도한 내용은 다음과 같습니다.

       var viewportWidth = $("body").innerWidth();
       var viewportHeight = $("body").innerHeight();

이 솔루션은 브라우저 스크롤바를 고려하지 않습니다.


답변:


160
$(window).height();
$(window).width();

더 많은 정보

그러나 이러한 값을 얻기 위해 jQuery를 사용하는 것은 필수가 아닙니다. 사용하다

document.documentElement.clientHeight;
document.documentElement.clientWidth;

스크롤바를 제외한 크기를 가져 오거나

window.innerHeight;
window.innerWidth;

스크롤바를 포함한 전체 뷰포트를 가져옵니다.

document.documentElement.clientHeight <= window.innerHeight;  // is always true

감사합니다 Kyle, 이것은 브라우저 스크롤바를 포함하지 않습니다.
Yetimwork Beyene

내가 이해하는 바에 따르면 브라우저의 '뷰포트'는 볼 수있는 것이 무엇이든간에 스크롤 막대에 내용이있을 수 없기 때문에 계산의 일부가 아니라고 가정합니다. 그러나 이것은 브라우저 작성자가 구현 한 방법에 따라 변경 될 수 있습니다.
Kyle

4
뷰포트는 사이트 창의 전체 너비 / 높이를 의미하는 것이 아니라 단지 뷰포트 일 뿐이며```window.innerHeight와 같은 것을 사용합니다. window.innerWidth;```
acidjazz

@Kyle 여기에 설명 된대로 완전히 정확합니다. w3schools.com/css/css_rwd_viewport.asp 뷰포트는 웹 페이지에서 사용자가 볼 수있는 영역입니다.
Brad Adams

1
렌더링 된 경우 수평 스크롤바를 포함하는 브라우저 창 뷰포트의 높이 (픽셀)입니다. . 출처 : developer.mozilla.org/en-US/docs/Web/API/Window/innerHeight
주었다는 점 parulian

36

jQuery를 사용하지 말고 올바른 결과를 위해 javascript를 사용하십시오.

여기에는 스크롤바 너비 / 높이가 포함됩니다.

var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;

alert('viewport width is: '+ windowWidth + ' and viewport height is:' + windowHeight);

스크롤바 너비 / 높이는 제외됩니다.

var widthWithoutScrollbar = document.body.clientWidth;
var heightWithoutScrollbar = document.body.clientHeight;

alert('viewport width is: '+ widthWithoutScrollbar + ' and viewport height is:' + heightWithoutScrollbar);


감사합니다. jQuery innerWidth 및 innerHeight 메서드는 실제로 잘못된 결과를 반환합니다.
jck

console.log (window.innerHeight); console.log (document.body.clientHeight); console.log ($ (window) .height ()); 마지막이 올바르지 않습니다. 귀하의 솔루션은 저에게 가장 좋습니다. 감사.
알리

25

다음은 대부분의 브라우저 (FF, Cr, IE6 +)에서 작동하는 일반 JS입니다.

var viewportHeight;
var viewportWidth;
if (document.compatMode === 'BackCompat') {
    viewportHeight = document.body.clientHeight;
    viewportWidth = document.body.clientWidth;
} else {
    viewportHeight = document.documentElement.clientHeight;
    viewportWidth = document.documentElement.clientWidth;
}

이것은 나에게만 효과적이었습니다. 창문. 높이는 내가 어떻게 계산할 수없는 무언가를주고있다.
Amit Kumar Gupta

11

잘못된 메서드 호출을 사용하고 있습니다. 뷰포트는 문서에 열려있는 "창"입니다. 볼 수있는 부분과 위치입니다.

를 사용 $(window).height()하면 뷰포트 크기가 제공되지 않고 전체 창 크기가 제공되며 일반적으로 문서가 더 클 수 있지만 전체 문서의 크기입니다.

실제 뷰포트의 크기를 얻으려면 window.innerHeightwindow.innerWidth.

https://gist.github.com/bohman/1351439

jQuery 메서드 (예 :) $(window).innerHeight()는 잘못된 숫자를 제공하므로 사용하지 마십시오 . 창 높이가 아니라 innerHeight.


9
창에 스크롤바 (브라우저에 의해 추가됨)가 있으면는 window.innerWidth뷰포트의 너비 + 스크롤바의 너비를 반환합니다. 이 상황에서 무엇을 할 수 있습니까?
Victor

8

기술

다음은 브라우저 뷰포트의 크기를 제공합니다.

견본

$(window).height();   // returns height of browser viewport
$(window).width();   // returns width of browser viewport

추가 정보


5

Kyle이 제안했듯이 이러한 방식으로 스크롤 막대의 크기를 고려하지 않고 클라이언트 브라우저 뷰포트 크기를 측정 할 수 있습니다.

샘플 (스크롤 막대가없는 뷰포트 치수)

// First you forcibly request the scroll bars to hidden regardless if they will be needed or not.
$('body').css('overflow', 'hidden');

// Take your measures.
// (These measures WILL NOT take into account scroll bars dimensions)
var heightNoScrollBars = $(window).height();
var widthNoScrollBars = $(window).width();

// Set the overflow css property back to it's original value (default is auto)
$('body').css('overflow', 'auto');

또는 스크롤 막대의 크기를 고려하면서 클라이언트 뷰포트의 크기를 찾으려면 다음 샘플이 가장 적합합니다.

먼저 body 태그를 100 % 너비와 높이로 설정하여 측정이 정확한지 확인하는 것을 잊지 마십시오.

body { 
width: 100%; // if you wish to measure the width and take into account the horizontal scroll bar.
height: 100%; // if you wish to measure the height while taking into account the vertical scroll bar.
}

샘플 (스크롤 막대가있는 뷰포트 치수)

// First you forcibly request the scroll bars to be shown regardless if they will be needed or not.
$('body').css('overflow', 'scroll');

// Take your measures.
// (These measures WILL take into account scroll bars dimensions)
var heightWithScrollBars = $(window).height();
var widthWithScrollBars = $(window).width();

// Set the overflow css property back to it's original value (default is auto)
$('body').css('overflow', 'auto');

4

스크립트 $(window).height()는 잘 작동하지만 (스크롤 높이가있는 문서가 아니라 뷰포트의 높이를 표시 함) 문서에 doctype 태그를 올바르게 삽입해야합니다 (예 : 다음 doctypes).

html5의 경우 : <!doctype html>

전환 HTML4의 경우 : <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

아마도 일부 브라우저에서 가정하는 기본 doctype $(window).height()은 브라우저의 높이가 아닌 문서의 높이를 사용합니다. doctype 사양을 사용하면 만족스럽게 해결되었으며 "스크롤 오버플로를 숨김으로 변경 한 다음 뒤로 변경"하는 것을 피할 수있을 것이라고 확신합니다. 즉, 미안합니다. t 미래의 프로그래머가 사용할 수 있도록 코드에 문서화합니다.

또한 스크립트를 작성하는 경우 라이브러리의 프로그래머를 돕기 위해 테스트를 만들 수 있습니다. 몇 가지를 만들어 보겠습니다.

$(document).ready(function() {
    if(typeof $=='undefined') {
        alert("Error, you haven't called JQuery library");
    }
    if(document.doctype==null || screen.height < parseInt($(window).height()) ) {
        alert("ERROR, check your doctype, the calculated heights are not what you might expect");
    } 
});

3
$(document).ready(function() {

  //calculate the window height & add css properties for height 100%

  wh = $( window ).height();

  ww = $( window ).width();

  $(".targeted-div").css({"height": wh, "width": ww});

});

0

jQuery 사용 ...

$ (document) .height () & $ (window) .height ()는 동일한 값을 반환합니다 ... 핵심은 스크롤이 발생하지 않도록 본문의 패딩과 여백을 재설정하는 것입니다.

<!--

body {
    padding: 0px;
    margin: 0px;
    position: relative;
}

-->

도움이 되었기를 바랍니다.


0

너비 화면과 작은 화면에 대해 내 웹 사이트의 다른 모양을 원했습니다. 2 개의 CSS 파일을 만들었습니다. Java에서는 화면 너비에 따라 2 개의 CSS 파일 중 어떤 파일이 사용되는지 선택합니다. -function 일부 자바 스크립트 echo에서 PHP 기능 을 사용합니다 echo.

<header>PHP 파일 섹션의 내 코드 :

<?php
echo "
<script>
    if ( window.innerWidth > 400)
            { document.write('<link href=\"kekemba_resort_stylesheetblog-jun2018.css\" rel=\"stylesheet\" type=\"text/css\">'); }
    else
            { document.write('<link href=\"kekemba_resort_stylesheetblog-jun2018small.css\" rel=\"stylesheet\" type=\"text/css\">'); }
</script>
"; 
?>
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.