내가 얻을 수있는 방법 windowWidth, windowHeight, pageWidth, pageHeight, screenWidth, screenHeight, pageX, pageY, screenX, screenY이는 모든 주요 브라우저에서 작동합니다?

내가 얻을 수있는 방법 windowWidth, windowHeight, pageWidth, pageHeight, screenWidth, screenHeight, pageX, pageY, screenX, screenY이는 모든 주요 브라우저에서 작동합니다?

답변:
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;
46css ( 'height') ( "46px") 와 같은 문자열이 아닌 숫자 ( )를 반환합니다 .
여기에는 알아야 할 모든 것이 있습니다 : 뷰포트 / 창 크기 얻기
그러나 간단히 말하면 :
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);
g = document.body?
document.body.
다음은 순수한 JavaScript ( Source )를 사용하는 크로스 브라우저 솔루션입니다 .
var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var height = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
body element값을 반환하기 때문에 더 좋습니다 undefined.
사용 가능한 화면 크기를 얻는 비 jQuery 방법입니다. window.screen.width/height이미 준비되었지만 반응 형 웹 디자인 및 완전성을 위해 이러한 속성을 언급 할 가치가 있다고 생각합니다.
alert(window.screen.availWidth);
alert(window.screen.availHeight);
http://www.quirksmode.org/dom/w3c_cssom.html#t10 :
availWidth and availHeight- 화면에서 사용 가능한 너비와 높이 (OS 작업 표시 줄 등 제외).
window.screen.availHeight일반 화면 모드가 강제로 스크롤되도록 전체 화면 모드를 가정하는 것 같습니다 (Firefox 및 Chrome에서 테스트).
window.screen.height대신 사용하십시오.
그러나 반응 형 화면에 대해 이야기하고 어떤 이유로 jQuery를 사용하여 화면을 처리하려는 경우,
window.innerWidth, window.innerHeight
정확한 측정을 제공합니다. 스크롤 막대의 여분의 공간을 제거하더라도 해당 공간을 조정할 필요가 없습니다. :)
window.innerWidth그리고 window.innerHeight계정에 스크롤 막대의 크기를 가지고 실패합니다. 스크롤 막대가 있으면 이러한 방법은 거의 모든 데스크탑 브라우저에서 창 크기에 대해 잘못된 결과를 반환합니다.
브라우저 도구 모음 및 기타 항목을 피하면서 WINDOW 너비와 높이를 얻을 수도 있습니다. 그것은이다 브라우저의 창에서 실제 사용할 수있는 공간 .
이렇게하려면 : window.innerWidth 및 window.innerHeight속성을 사용
하십시오 ( w3schools의 doc 참조 ).
대부분의 경우, 예를 들어 완벽하게 중앙에 떠있는 부동 모달 대화 상자를 표시하는 것이 가장 좋은 방법입니다. 브라우저를 사용하는 해상도 방향 또는 창 크기에 관계없이 창에서 위치를 계산할 수 있습니다.
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>');
높이와 사용하는 웹 사이트의 현재로드 된 페이지의 폭을 확인하려면 "콘솔을" 또는 클릭 한 후 "검사" .
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)
문서의 폭과 높이합니다 (대한 진정한 방탄 솔루션을 필요로하는 경우 pageWidth와 pageHeight그림에), 당신은 내 플러그인을 사용하여 고려할 수 있습니다 jQuery.documentSize을 .
jQuery 및 기타 메소드가 실패하는 경우에도 항상 올바른 문서 크기를 리턴하는 것이 한 가지 목적이 있습니다 . 이름에도 불구하고, 반드시 jQuery를 사용할 필요는 없습니다. – 바닐라 자바 스크립트로 작성되었으며 jQuery 없이도 작동합니다 .
용법:
var w = $.documentWidth(),
h = $.documentHeight();
세계를 위해 document. 액세스 권한이있는 내장 iframe과 같은 다른 문서의 경우 문서를 매개 변수로 전달하십시오.
var w = $.documentWidth( myIframe.contentDocument ),
h = $.documentHeight( myIframe.contentDocument );
업데이트 : 이제 창 크기에도 적용됩니다.
버전 1.1.0부터 jQuery.documentSize는 창 크기도 처리합니다.
그 때문에 필요합니다
$( window ).height()입니다 아이폰 OS의 버그는 쓸모가되는 지점으로,$( window ).width()하고 $( window ).height()있는 모바일 신뢰할 수없는 그들이 모바일 줌의 영향을 처리하지 못하기 때문이다.jQuery.documentSize을 제공 $.windowWidth()하고 $.windowHeight()이러한 문제를 해결한다. 자세한 내용 은 설명서 를 확인하십시오 .
크기를 표시하는 데 사용할 수있는 작은 자바 스크립트 북마크를 작성했습니다. 브라우저에 쉽게 추가 할 수 있으며 클릭 할 때마다 브라우저 창의 오른쪽 모서리에 크기가 표시됩니다.
여기에서 북마크릿을 사용하는 방법에 대한 정보를 찾을 수 있습니다 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 앞에 있습니다.
반응 형 레이아웃과 관련된 일부 경우 $(document).height()에는보기 포트 높이 만 표시하는 잘못된 데이터가 반환 될 수 있습니다. 예를 들어 일부 div # wrapper의 높이가 100 % 인 경우 해당 #wrapper는 내부의 일부 블록으로 확장 될 수 있습니다. 그러나 높이는 여전히 뷰포트 높이와 같습니다. 이러한 상황에서는 다음을 사용할 수 있습니다
$('#wrapper').get(0).scrollHeight
랩퍼의 실제 크기를 나타냅니다.
화면 크기와 관련된 전체 안내서
자바 스크립트
높이 :
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 (i.e. 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.)
참고 : 창이 최대화되면 화면과 같습니다.
너비의 경우 :
document.body.clientWidth // Full width of the HTML page as coded, minus the vertical scroll bar
screen.width // Device screen width (i.e. 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)
jquery
높이 :
$(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)
뷰포트 크기는 장치에서 일치하지 않으며 (이에 대한 모든 연구 결과에 따라) 해당 게시물의 모든 답변에 의존 할 수 없기 때문에 데스크톱 및 모바일 브라우저의 실제 뷰 포트 크기를 알 수있는 라이브러리를 개발했습니다. : https : // github .com / pyrsmk / W
때때로 창과 내부 내용의 크기를 조정하는 동안 너비 / 높이 변화를 확인해야합니다.
이를 위해 모든 크기 조정 및 거의 즉시 업데이트를 동적으로 모니터링하는 로그 상자를 추가하는 작은 스크립트를 작성했습니다.
고정 된 위치와 높은 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가없는 솔루션입니다. :)
의 도입 globalThis에 ES2020 당신은 같은 속성을 사용할 수 있습니다.
화면 크기 :
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)
이것을 얻기 위해 Screen 객체를 사용할 수 있습니다 .
다음은 반환되는 예입니다.
Screen {
availWidth: 1920,
availHeight: 1040,
width: 1920,
height: 1080,
colorDepth: 24,
pixelDepth: 24,
top: 414,
left: 1920,
availTop: 414,
availLeft: 1920
}
당신의 얻으려면 screenWidth변수를 바로 사용 screen.width과 동일을 screenHeight, 그냥 사용합니다 screen.height.
창 너비와 높이를 얻으려면 각각 screen.availWidth또는 screen.availHeight각각입니다.
의 경우 pageX와 pageY변수를 사용합니다 window.screenX or Y. 이것은 왼쪽 / 최상위 화면 의 매우 왼쪽 / 위에서 가져온 것 입니다. 따라서 너비가 두 개인 화면이 1920있는 경우 오른쪽 화면 왼쪽에서 500px 인 창에는 X 값이 2420(1920 + 500)이됩니다. screen.width/height그러나 CURRENT 화면의 너비 또는 높이를 표시하십시오.
페이지의 폭과 높이를 얻으려면, jQuery의를 사용 $(window).height()하거나 $(window).width().
다시 jQuery를 사용 하여 및 값에 $("html").offset().topand $("html").offset().left를 사용 하십시오 .pageXpageY
// 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();
})();
이것은 React JS Project에서 화면 너비를 얻는 방법입니다.
너비가 1680이면 570을 반환하고 그렇지 않으면 200을 반환
var screenWidth = window.screen.availWidth;
<Label style={{ width: screenWidth == "1680" ? 570 : 200, color: "transparent" }}>a </Label>