모든 주요 브라우저에서 작동하는 windowWidth
, windowHeight
, pageWidth
, pageHeight
, screenWidth
, screenHeight
, pageX
, pageY
, screenX
, screenY
질문자 :turtledove
jQuery를 사용하여 창 또는 문서의 크기를 얻을 수 있습니다.
// Size of browser viewport. $(window).height(); $(window).width(); // Size of HTML document (same as pageHeight/pageWidth in screenshot). $(document).height(); $(document).width();
화면 크기의 경우 screen
객체를 사용할 수 있습니다.
window.screen.height; window.screen.width;
Ankit Jaiswal
여기에는 알아야 할 모든 것이 있습니다. 뷰포트/창 크기 가져오기
하지만 간단히 말해서:
var win = window, doc = document, docElem = doc.documentElement, body = doc.getElementsByTagName('body')[0], x = win.innerWidth || docElem.clientWidth || body.clientWidth, y = win.innerHeight|| docElem.clientHeight|| body.clientHeight; alert(x + ' × ' + y);
이 답변 편집을 중지하십시오. 다른 사람들이 자신의 코드 형식 기본 설정과 일치하도록 22번 편집했습니다. 최신 브라우저만 대상으로 하려는 경우에는 이것이 필요하지 않다는 점도 지적되었습니다. 그렇다면 다음만 필요합니다.
const width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; const height = window.innerHeight|| document.documentElement.clientHeight|| document.body.clientHeight; console.log(width, height);
sidonaldson
다음은 순수 JavaScript ( Source )를 사용한 크로스 브라우저 솔루션입니다.
var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
confile
사용 가능한 화면 크기를 가져오는 비 jQuery 방법입니다. window.screen.width/height
는 이미 설정되었지만 반응형 웹 디자인과 완성도를 위해 이러한 속성을 언급할 가치가 있다고 생각합니다.
alert(window.screen.availWidth); alert(window.screen.availHeight);
http://www.quirksmode.org/dom/w3c_cssom.html#t10 :
availWidth 및 availHeight - 화면에서 사용 가능한 너비와 높이입니다(OS 작업 표시줄 등 제외).
Daniel W.
그러나 반응형 화면에 대해 이야기하고 어떤 이유로 jQuery를 사용하여 처리하려는 경우,
window.innerWidth, window.innerHeight
정확한 측정을 제공합니다. 스크롤 막대의 추가 공간을 제거하더라도 해당 공간을 조정하는 것에 대해 걱정할 필요가 없습니다. :)
Aabha Pandey
전체 2020
나는 그 질문이 약 10년 동안 지속되었다는 사실에 놀랐고 지금까지 아무도 완전한 답변(10개 값 포함)을 아직 제공하지 않은 것처럼 보입니다. 그래서 OP 질문(특히 그림)을 주의 깊게 분석하고 몇 가지 의견을
-
(0,0)
중심은 뷰포트(막대와 주 테두리가 없는 브라우저 창)에 있고 축은 오른쪽과 아래쪽(OP 그림에 표시된 것)으로pageX, pageY, screenX, screenY
는 음수여야 합니다(또는 페이지가 작거나 스크롤되지 않은 경우 0). - for
screenHeight/Width
OP는 시스템 메뉴 표시줄을 포함하여 화면 높이/너비를 계산하려고 합니다(예: MacOs에서) - 이것이 우리가.availWidth/Height
사용하지 않는 이유입니다(이를 계산하지 않음) -
windowWidth/Height
OP의 경우 스크롤 막대의 크기를 계산하지 않으므로.clientWidth/Height
-
screenY
- 아래 솔루션에서 왼쪽 상단 브라우저 모서리(window.screenY
)의 메뉴/테이블/URL 표시줄 높이에 추가합니다. 그러나 브라우저에 다운로드 하단 막대가 표시되거나 페이지 하단에 개발자 콘솔이 열려 있는 경우 해당 값을 계산하기가 어렵습니다. 이 경우 이 값은 아래 솔루션에서 해당 막대/콘솔 높이의 크기가 증가합니다. 아마도 수정하기 위해 막대/콘솔 높이 값을 읽는 것은 불가능할 것입니다(측정하기 전에 막대/콘솔을 닫으라고 사용자에게 묻는 것과 같은 트릭 없이...) -
pageWidth
- pageWidth가 windowWidth보다 작은 경우 이 값을 얻기 위해<body>
contentWidth
에서 예제 계산을 수행하지만 일반적으로 이 경우 어려울 수 있음) -
<body>
margin=0이라고 가정합니다.pageWidth/Height
및pageX/Y
계산할 때 이 값을 고려해야 합니다.
function sizes() { let contentWidth = [...document.body.children].reduce( (a, el) => Math.max(a, el.getBoundingClientRect().right), 0) - document.body.getBoundingClientRect().x; return { windowWidth: document.documentElement.clientWidth, windowHeight: document.documentElement.clientHeight, pageWidth: Math.min(document.body.scrollWidth, contentWidth), pageHeight: document.body.scrollHeight, screenWidth: window.screen.width, screenHeight: window.screen.height, pageX: document.body.getBoundingClientRect().x, pageY: document.body.getBoundingClientRect().y, screenX: -window.screenX, screenY: -window.screenY - (window.outerHeight-window.innerHeight), } } // TEST function show() { console.log(sizes()); }
body { margin: 0 } .box { width: 3000px; height: 4000px; background: red; }
<div class="box"> CAUTION: stackoverflow snippet gives wrong values for screenX-Y, but if you copy this code to your page directly the values will be right<br> <button onclick="show()" style="">CALC</button> </div>
MacOs High Sierra의 Chrome 83.0, Safari 13.1, Firefox 77.0 및 Edge 83.0에서 테스트합니다.
Kamil Kiełczewski
function wndsize(){ var w = 0;var h = 0; //IE if(!window.innerWidth){ if(!(document.documentElement.clientWidth == 0)){ //strict mode w = document.documentElement.clientWidth;h = document.documentElement.clientHeight; } else{ //quirks mode w = document.body.clientWidth;h = document.body.clientHeight; } } else { //w3c w = window.innerWidth;h = window.innerHeight; } return {width:w,height:h}; } function wndcent(){ var hWnd = (arguments[0] != null) ? arguments[0] : {width:0,height:0}; var _x = 0;var _y = 0;var offsetX = 0;var offsetY = 0; //IE if(!window.pageYOffset){ //strict mode if(!(document.documentElement.scrollTop == 0)){offsetY = document.documentElement.scrollTop;offsetX = document.documentElement.scrollLeft;} //quirks mode else{offsetY = document.body.scrollTop;offsetX = document.body.scrollLeft;}} //w3c else{offsetX = window.pageXOffset;offsetY = window.pageYOffset;}_x = ((wndsize().width-hWnd.width)/2)+offsetX;_y = ((wndsize().height-hWnd.height)/2)+offsetY; return{x:_x,y:_y}; } var center = wndcent({width:350,height:350}); document.write(center.x+';<br>'); document.write(center.y+';<br>'); document.write('<DIV align="center" id="rich_ad" style="Z-INDEX: 10; left:'+center.x+'px;WIDTH: 350px; POSITION: absolute; TOP: '+center.y+'px; HEIGHT: 350px"><!--К сожалению, у Вас не установлен flash плеер.--></div>');
dude
브라우저 도구 모음 및 기타 항목을 피하면서 WINDOW 너비와 높이를 얻을 수도 있습니다. 브라우저 창에서 실제 사용 가능한 영역입니다 .
이렇게 하려면 window.innerWidth
및 window.innerHeight
속성을 사용합니다( w3schools 문서 참조 ).
대부분의 경우 예를 들어 완벽하게 중앙에 있는 부동 모달 대화 상자를 표시하는 것이 가장 좋은 방법입니다. 브라우저를 사용하는 해상도 방향이나 창 크기에 관계없이 창의 위치를 계산할 수 있습니다.
serfer2
"콘솔"을 사용 하거나 "검사"를 클릭한 후 웹사이트의 현재 로드된 페이지의 높이와 너비를 확인하려면 .
1단계 : 마우스 오른쪽 버튼을 클릭하고 '검사'를 클릭한 다음 '콘솔'을 클릭합니다.
2단계 : 브라우저 화면이 '최대화' 모드에 있지 않아야 합니다. 브라우저 화면이 '최대화' 모드에 있는 경우 먼저 최대화 버튼(오른쪽 또는 왼쪽 상단 모서리에 있음)을 클릭하고 최대화를 해제해야 합니다.
3단계 : 이제 보다 큼 기호('>') 뒤에 다음을 작성합니다.
> window.innerWidth output : your present window width in px (say 749) > window.innerHeight output : your present window height in px (say 359)
solanki...
Community Wiki
화면 크기와 관련된 전체 가이드
자바스크립트
높이:
document.body.clientHeight // Inner height of the HTML document body, including padding // but not the horizontal scrollbar height, border, or margin screen.height // Device screen height (ie all physically visible stuff) screen.availHeight // Device screen height minus the operating system taskbar (if present) window.innerHeight // The current document's viewport height, minus taskbars, etc. window.outerHeight // Height the current window visibly takes up on screen // (including taskbars, menus, etc.)
참고: 창이 최대화되면 screen.availHeight와 같습니다.
너비:
document.body.clientWidth // Full width of the HTML page as coded, minus the vertical scroll bar screen.width // Device screen width (ie all physically visible stuff) screen.availWidth // Device screen width, minus the operating system taskbar (if present) window.innerWidth // The browser viewport width (including vertical scroll bar, includes padding but not border or margin) window.outerWidth // The outer window width (including vertical scroll bar, // toolbars, etc., includes padding and border but not margin)
제이쿼리
높이:
$(document).height() // Full height of the HTML page, including content you have to // scroll to see $(window).height() // The current document's viewport height, minus taskbars, etc. $(window).innerHeight() // The current document's viewport height, minus taskbars, etc. $(window).outerHeight() // The current document's viewport height, minus taskbars, etc.
너비:
$(document).width() // The browser viewport width, minus the vertical scroll bar $(window).width() // The browser viewport width (minus the vertical scroll bar) $(window).innerWidth() // The browser viewport width (minus the vertical scroll bar) $(window).outerWidth() // The browser viewport width (minus the vertical scroll bar)
Hamza Iftikhar
문서 너비와 높이(그림의 pageWidth
및 pageHeight
에 대한 진정한 방탄 솔루션이 필요한 경우 내 플러그인인 jQuery.documentSize 사용을 고려할 수 있습니다.
jQuery 및 기타 메서드가 실패하는 시나리오에서도 항상 올바른 문서 크기를 반환하는 한 가지 목적이 있습니다. 이름에도 불구하고 jQuery를 반드시 사용할 필요는 없습니다. 이는 기본 Javascript로 작성되었으며 jQuery 없이도 작동합니다 .
용법:
var w = $.documentWidth(), h = $.documentHeight();
글로벌 document
. 액세스 권한이 있는 포함된 iframe과 같은 다른 문서의 경우 문서를 매개변수로 전달합니다.
var w = $.documentWidth( myIframe.contentDocument ), h = $.documentHeight( myIframe.contentDocument );
업데이트: 이제 창 크기도 마찬가지입니다.
버전 1.1.0 이후로 jQuery.documentSize는 창 크기도 처리합니다.
그것이 필요하기 때문에
-
$( window ).height()
는 iOS 에서 버그가 있어 쓸모가 없습니다. -
$( window ).width()
및$( window ).height()
는 모바일 확대/축소 효과를 처리하지 않기 때문에 모바일에서 신뢰할 수 없습니다.
jQuery.documentSize는 이러한 문제를 해결 $.windowWidth()
및 $.windowHeight()
자세한 내용은 설명서 를 확인하십시오.
hashchange
크기를 표시하는 데 사용할 수 있는 작은 자바스크립트 북마크를 작성했습니다. 브라우저에 쉽게 추가할 수 있으며 클릭할 때마다 브라우저 창의 오른쪽 모서리에 크기가 표시됩니다.
여기에서 북마크릿 사용 방법에 대한 정보를 찾을 수 있습니다. https://en.wikipedia.org/wiki/Bookmarklet
책갈피
javascript:(function(){!function(){var i,n,e;return n=function(){var n,e,t;return t="background-color:azure; padding:1rem; position:fixed; right: 0; z-index:9999; font-size: 1.2rem;",n=i('<div style="'+t+'"></div>'),e=function(){return'<p style="margin:0;">width: '+i(window).width()+" height: "+i(window).height()+"</p>"},n.html(e()),i("body").prepend(n),i(window).resize(function(){n.html(e())})},(i=window.jQuery)?(i=window.jQuery,n()):(e=document.createElement("script"),e.src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js",e.onload=n,document.body.appendChild(e))}()}).call(this);
원본 코드
원래 코드는 커피에 있습니다.
(-> addWindowSize = ()-> style = 'background-color:azure; padding:1rem; position:fixed; right: 0; z-index:9999; font-size: 1.2rem;' $windowSize = $('<div style="' + style + '"></div>') getWindowSize = -> '<p style="margin:0;">width: ' + $(window).width() + ' height: ' + $(window).height() + '</p>' $windowSize.html getWindowSize() $('body').prepend $windowSize $(window).resize -> $windowSize.html getWindowSize() return if !($ = window.jQuery) # typeof jQuery=='undefined' works too script = document.createElement('script') script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' script.onload = addWindowSize document.body.appendChild script else $ = window.jQuery addWindowSize() )()
기본적으로 코드는 창 크기를 조정할 때 업데이트되는 작은 div를 앞에 추가합니다.
Andi Giga
globalThis
에 globalThis 가 도입되면서 다음과 같은 속성을 사용할 수 있습니다.
화면 크기:
globalThis.screen.availWidth globalThis.screen.availHeight
창 크기의 경우
globalThis.outerWidth globalThis.outerHeight
오프셋의 경우:
globalThis.pageXOffset globalThis.pageYOffset
...& 곧.
alert("Screen Width: "+ globalThis.screen.availWidth +"\nScreen Height: "+ globalThis.screen.availHeight)
Prashant Gupta
반응형 레이아웃과 관련된 일부 경우 $(document).height()
는 뷰 포트 높이만 표시하는 잘못된 데이터를 반환할 수 있습니다. 예를 들어 일부 div#wrapper의 높이가 100%인 경우 해당 #wrapper는 내부 블록만큼 늘어날 수 있습니다. 그러나 높이는 여전히 뷰포트 높이와 같습니다. 그런 상황에서 당신은 사용할 수 있습니다
$('#wrapper').get(0).scrollHeight
이는 래퍼의 실제 크기를 나타냅니다.
Akim Kelar
데스크톱 및 모바일 브라우저의 실제 표시 영역 크기를 알기 위한 라이브러리를 개발했습니다. 표시 영역 크기가 장치 간에 일치하지 않고 해당 게시물의 모든 답변에 의존할 수 없기 때문입니다(이에 대해 내가 수행한 모든 연구에 따르면). https://github .com/pyrsmk/W
pyrsmk
때때로 창과 내부 콘텐츠의 크기를 조정하는 동안 너비/높이가 변경되는 것을 확인해야 합니다.
이를 위해 모든 크기 조정 및 거의 즉시 업데이트를 동적으로 모니터링하는 로그 상자를 추가하는 작은 스크립트를 작성했습니다.
고정 위치와 높은 z-색인이 있는 유효한 HTML을 추가하지만 충분히 작기 때문에 다음을 수행할 수 있습니다 .
- 실제 사이트에서 사용
- 모바일/반응형 보기 테스트에 사용
테스트 대상: Chrome 40, IE11, 하지만 다른/이전 브라우저에서도 작동할 가능성이 높습니다... :)
function gebID(id){ return document.getElementById(id); } function gebTN(tagName, parentEl){ if( typeof parentEl == "undefined" ) var parentEl = document; return parentEl.getElementsByTagName(tagName); } function setStyleToTags(parentEl, tagName, styleString){ var tags = gebTN(tagName, parentEl); for( var i = 0; i<tags.length; i++ ) tags[i].setAttribute('style', styleString); } function testSizes(){ gebID( 'screen.Width' ).innerHTML = screen.width; gebID( 'screen.Height' ).innerHTML = screen.height; gebID( 'window.Width' ).innerHTML = window.innerWidth; gebID( 'window.Height' ).innerHTML = window.innerHeight; gebID( 'documentElement.Width' ).innerHTML = document.documentElement.clientWidth; gebID( 'documentElement.Height' ).innerHTML = document.documentElement.clientHeight; gebID( 'body.Width' ).innerHTML = gebTN("body")[0].clientWidth; gebID( 'body.Height' ).innerHTML = gebTN("body")[0].clientHeight; } var table = document.createElement('table'); table.innerHTML = "<tr><th>SOURCE</th><th>WIDTH</th><th>x</th><th>HEIGHT</th></tr>" +"<tr><td>screen</td><td id='screen.Width' /><td>x</td><td id='screen.Height' /></tr>" +"<tr><td>window</td><td id='window.Width' /><td>x</td><td id='window.Height' /></tr>" +"<tr><td>document<br>.documentElement</td><td id='documentElement.Width' /><td>x</td><td id='documentElement.Height' /></tr>" +"<tr><td>document.body</td><td id='body.Width' /><td>x</td><td id='body.Height' /></tr>" ; gebTN("body")[0].appendChild( table ); table.setAttribute( 'style', "border: 2px solid black !important; position: fixed !important;" +"left: 50% !important; top: 0px !important; padding:10px !important;" +"width: 150px !important; font-size:18px; !important" +"white-space: pre !important; font-family: monospace !important;" +"z-index: 9999 !important;background: white !important;" ); setStyleToTags(table, "td", "color: black !important; border: none !important; padding: 5px !important; text-align:center !important;"); setStyleToTags(table, "th", "color: black !important; border: none !important; padding: 5px !important; text-align:center !important;"); table.style.setProperty( 'margin-left', '-'+( table.clientWidth / 2 )+'px' ); setInterval( testSizes, 200 );
편집: 이제 스타일은 모든 테이블이 아닌 로거 테이블 요소에만 적용됩니다. 또한 이것은 jQuery가 없는 솔루션입니다. :)
jave.web
이것을 얻기 위해 Screen 객체를 사용할 수 있습니다.
다음은 반환되는 내용의 예입니다.
Screen { availWidth: 1920, availHeight: 1040, width: 1920, height: 1080, colorDepth: 24, pixelDepth: 24, top: 414, left: 1920, availTop: 414, availLeft: 1920 }
screenWidth 변수를 얻으려면 screenWidth
사용하고 screen.width
와 동일하게 screenHeight
만 사용 screen.height
됩니다.
창 너비와 높이를 얻으려면 screen.availWidth
또는 screen.availHeight
됩니다.
pageX
및 pageY
변수의 경우 window.screenX or Y
. 이것은 VERY LEFT/TOP OF OF your LEFT/TOP-est SCREEN 에서 가져온 것입니다. 1920
두 개의 화면이 있는 경우 오른쪽 화면 왼쪽에서 500px 떨어진 창의 X 값은 2420
(1920+500)이 됩니다. screen.width/height
는 현재 화면의 너비 또는 높이를 표시합니다.
페이지의 너비와 높이를 얻으려면 jQuery의 $(window).height()
또는 $(window).width()
.
다시 jQuery를 사용 pageX
및 pageY
값에 $("html").offset().top
및 $("html").offset().left
를 사용합니다.
Zach Barham
여기 내 솔루션이 있습니다!
// innerWidth const screen_viewport_inner = () => { let w = window, i = `inner`; if (!(`innerWidth` in window)) { i = `client`; w = document.documentElement || document.body; } return { width: w[`${i}Width`], height: w[`${i}Height`] } }; // outerWidth const screen_viewport_outer = () => { let w = window, o = `outer`; if (!(`outerWidth` in window)) { o = `client`; w = document.documentElement || document.body; } return { width: w[`${o}Width`], height: w[`${o}Height`] } }; // style const console_color = ` color: rgba(0,255,0,0.7); font-size: 1.5rem; border: 1px solid red; `; // testing const test = () => { let i_obj = screen_viewport_inner(); console.log(`%c screen_viewport_inner = \n`, console_color, JSON.stringify(i_obj, null, 4)); let o_obj = screen_viewport_outer(); console.log(`%c screen_viewport_outer = \n`, console_color, JSON.stringify(o_obj, null, 4)); }; // IIFE (() => { test(); })();
user8202629
React JS 프로젝트에서 화면 너비를 얻는 방법은 다음과 같습니다.
너비가 1680이면 570을 반환하고 그렇지 않으면 200을 반환합니다.
var screenWidth = window.screen.availWidth; <Label style={{ width: screenWidth == "1680" ? 570 : 200, color: "transparent" }}>a </Label>
Prashant Yalatwar
출처 : http:www.stackoverflow.com/questions/3437786/get-the-size-of-the-screen-current-web-page-and-browser-window
'etc. > StackOverFlow' 카테고리의 다른 글
MS Word에서 format 및 syntax highlight를 유지하는 code snippets을 표시하는 방법 (0) | 2021.11.24 |
---|---|
3의 법칙이란? (0) | 2021.11.24 |
MVP와 MVC는 무엇이며 차이점은 무엇입니까? (0) | 2021.11.24 |
.gitignore와 .gitkeep의 차이점은 무엇입니까? (0) | 2021.11.24 |
Homebrew는 특정 버전의 수식을 설치합니까? (0) | 2021.11.24 |