Uzyskaj rozmiar ekranu, bieżącej strony internetowej i okna przeglądarki

Jak mogę uzyskać windowWidth, windowHeight, pageWidth, pageHeight, screenWidth, screenHeight, pageX, pageY, screenX, screenY, które będą działać we wszystkich głównych przeglądarkach?

Rozwiązanie

Możesz uzyskać rozmiar okna lub dokumentu za pomocą jQuery:

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

// Size of HTML document (same as pageHeight/pageWidth in screenshot).
$(document).height();
$(document).width();

Dla rozmiaru ekranu możesz użyć obiektu screen:

window.screen.height;
window.screen.width;
Komentarze (21)

To zawiera wszystko, co musisz wiedzieć: Get viewport/window size

, ale w skrócie:

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

Skrzypce

Proszę przestać edytować tę odpowiedź. To's być edytowane 20 razy teraz przez różnych ludzi, aby dopasować ich preferencje formatu kodu. It's also been pointed out that this isn't required if you only want to target modern browsers - if so you only need the following:

const width  = window.innerWidth || document.documentElement.clientWidth || 
document.body.clientWidth,
const height = window.innerHeight|| document.documentElement.clientHeight|| 
document.body.clientHeight;

console.log(width, height);
Komentarze (14)
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"></div>');
Komentarze (0)