programing

화면 크기, 현재 웹 페이지 및 브라우저 창 가져오기

itsource 2022. 9. 28. 23:38
반응형

화면 크기, 현재 웹 페이지 및 브라우저 창 가져오기

어떻게 하면 얻을 수 있나요?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();

화면 크기에 대해 개체를 사용할 수 있습니다.

window.screen.height;
window.screen.width;

여기에 당신이 알아야 할 모든 것이 있습니다.뷰포트/창 크기 가져오기

요컨대:

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);

다음은 순수 JavaScript(소스)를 사용하는 크로스 브라우저 솔루션입니다.

var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var height = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

사용 가능한 화면 치수를 얻기 위한 jQuery 이외의 방법입니다. window.screen.width/height이미 공개되어 있습니다만, 응답성이 뛰어난 Web 설계와 완전성을 위해서, 이러한 특성을 언급할 필요가 있다고 생각합니다.

alert(window.screen.availWidth);
alert(window.screen.availHeight);

http://www.quirksmode.org/dom/w3c_cssom.html#t10 :

가용성 폭 및 가용성높이 - 화면에 표시되는 사용 가능한 폭과 높이(OS 태스크바 등 제외).

하지만 반응하는 화면에 대해 이야기할 때, 그리고 어떤 이유로든 jQuery를 사용하여 처리하고 싶다면,

window.innerWidth, window.innerHeight

올바른 측정을 제공합니다.스크롤 막대의 여유 공간을 제거해도 공간을 조정할 필요가 없습니다.

풀 2020

나는 그 질문이 10년 정도 된 것에 놀랐고 아직 아무도 완전한 답을 하지 못한 것 같다(10개의 가치로).그래서 저는 OP 질문(특히 사진)을 꼼꼼히 분석해서 몇 가지 의견을 말씀드리겠습니다.

  • (0,0) 및 테두리가 창의 왼쪽 과 아래쪽그림에 것에 의 은 OP입니다.pageX, pageY, screenX, screenY음수여야 합니다(페이지가 작거나 스크롤되지 않은 경우 0).
  • ★★★★★★에screenHeight/Width 높이(MacOs의 등에 OP는 하지 않습니다.이 때문에 사용하지 않습니다..availWidth/Height하지 않는다
  • ★★★★★★에windowWidth/Height를 사용합니다..clientWidth/Height
  • screenY모서리 합니다(- 「」 「」 「」 「」 「」window.screenY'/'/'/url''입니다.단, 브라우저에 다운로드 하단의 막대가 표시되는 경우 및/또는 페이지 하단의 개발자 콘솔이 열려 있는 경우 이 값을 계산하는 것은 어렵습니다.이 경우 이 값은 아래 솔루션에서 해당 막대/콘솔 높이의 크기만큼 증가합니다.아마도 보정을 위해 막대/콘솔 높이 값을 읽는 것은 불가능할 것입니다(측정 전에 막대/콘솔을 닫으라고 사용자에게 요청하는 것과 같은 트릭이 없으면...).
  • pageWidthwindow-pageWidth보다 작을 (을 수동으로 계산해야 함)<body>을 취득하기 children elements(로 ).contentWidth아래 솔루션에서 - 그러나 일반적으로는 이 작업이 어려울 수 있습니다.)
  • 간단히 말하면, 나는 라고 생각한다.<body>- 이 .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에서 테스트합니다.

그래피컬한 답변: (................)

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>');

또한 WINDOW의 너비와 높이를 얻을 수 있어 브라우저 툴바 등의 조작을 피할 수 있습니다.브라우저 창에서 실제 사용 가능한 영역입니다.

, 다음과 같이 사용합니다.window.innerWidth ★★★★★★★★★★★★★★★★★」window.innerHeight속성(w3documents 참조).

예를 들어 대부분의 경우 완전히 중심에 있는 부동 모달 대화 상자를 표시하는 것이 가장 좋습니다.브라우저를 사용하는 해상도 방향이나 창 크기에 관계없이 창의 위치를 계산할 수 있습니다.

"콘솔"을 사용하거나 "검사"를 클릭한 후 웹 사이트의 현재 로드된 페이지의 높이와 너비를 확인합니다.

1단계: 마우스 오른쪽 버튼을 클릭하고 'Inspect'를 클릭한 다음 'console'을 클릭합니다.

2단계: 브라우저 화면이 '최대화' 모드가 아닌지 확인합니다.브라우저 화면이 '최대화' 모드인 경우 먼저 최대화 버튼(오른쪽 또는 왼쪽 상단 모서리에 있음)을 클릭하여 최대화를 해제해야 합니다.

스텝 3: 다음으로 큰 기호('>') 뒤에 다음과 같이 입력합니다.

       > window.innerWidth
            output : your present window width in px (say 749)

       > window.innerHeight
            output : your present window height in px (say 359)

화면 크기에 관한 전체 가이드

자바스크립트

높이:

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)

쿼리

높이:

$(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://help.optimizely.com/Build_Campaigns_and_Experiments/Use_screen_measurements_to_design_for_responsive_breakpoints

높이에 (「 」 「 」 「 」 「 」 「 」 「 」).pageWidth ★★★★★★★★★★★★★★★★★」pageHeightmine 플러그인 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()이러한 문제를 해결합니다.상세한 것에 대하여는, 문서를 참조해 주세요.

「 」의 globalThisES2020에서는 다음과 같은 속성을 사용할 수 있습니다.

화면 크기:

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)

사이즈 표시에 사용할 수 있는 작은 Javascript 북마크렛을 작성했습니다.브라우저에 쉽게 추가할 수 있으며 클릭할 때마다 브라우저 창의 오른쪽 구석에 크기가 표시됩니다.

여기에서는 북마크릿의 사용 방법에 대해 설명합니다.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 #' 'Div #' '100%' '#Div #' 'Div #' 'Div #' 'Div #' '다'하지만 높이는 뷰포트 높이와 같을 거예요.를 사용할 수 있습니다.

$('#wrapper').get(0).scrollHeight

그것은 포장지의 실제 크기를 나타냅니다.

저는 데스크톱과 모바일 브라우저의 실제 뷰포트 크기를 알기 위한 라이브러리를 개발했습니다.뷰포트 크기는 디바이스 간에 일관성이 없기 때문에 이 게시물의 모든 답변에 의존할 수 없기 때문입니다.https://github.com/pyrsmk/W

창과 내부 컨텐츠의 크기를 조정하는 동안 너비/높이가 변경되는 것을 확인해야 하는 경우가 있습니다.

그 때문에, 로그 박스를 추가하는 스크립트를 작성했습니다.로그 박스는 모든 사이즈 변경과 거의 즉시 갱신을 동적으로 감시합니다.

고정 위치와 높은 z-index를 가진 유효한 HTML을 추가하지만 충분히 작기 때문에 다음을 수행할 수 있습니다.

  • 그것을 실제 현장에서 사용하다
  • 모바일 뷰/응답테스트에 사용


Chrome 40, IE11., 른 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가 필요 없는 솔루션입니다.

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 오른쪽 의 창 는 X .2420(1500+500). screen.width/height전류

jQuery를 합니다.$(window).height() ★★★★★★★★★★★★★★★★★」$(window).width().

jQuery를 사용하여 "da" jQuery"를 합니다.$("html").offset().top ★★★★★★★★★★★★★★★★★」$("html").offset().left★★★★★★★★★★★★★★★★★★에pageX ★★★★★★★★★★★★★★★★★」pageY★★★★★★ 。

여기 내 해결책이 있다!

// 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();
})();

리액트 JS 프로젝트에서 화면 폭을 얻는 방법은 다음과 같습니다.

폭이 1680과 같으면 570을 반환하고 그렇지 않으면 200을 반환합니다.

var screenWidth = window.screen.availWidth;

<Label style={{ width: screenWidth == "1680" ? 570 : 200, color: "transparent" }}>a  </Label>

Screen.availWidth

언급URL : https://stackoverflow.com/questions/3437786/get-the-size-of-the-screen-current-web-page-and-browser-window

반응형