简体   繁体   中英

Get the available browser window size (clientHeight/clientWidth) consistently across multiple browsers

I would like a method of getting the available window size across multiple browsers without using jQuery/Mootools/any third-party library dependencies. I've done a little research on this but half the things I've come across talk about Netscape Navigator...

Just wondering if someone out there has more recent advice.

usage

var width = getWindowSize().width;

code

var getWindowSize = (function() {
  var docEl = document.documentElement,
      IS_BODY_ACTING_ROOT = docEl && docEl.clientHeight === 0;

  // Used to feature test Opera returning wrong values 
  // for documentElement.clientHeight. 
  function isDocumentElementHeightOff () { 
      var d = document,
          div = d.createElement('div');
      div.style.height = "2500px";
      d.body.insertBefore(div, d.body.firstChild);
      var r = d.documentElement.clientHeight > 2400;
      d.body.removeChild(div);
      return r;
  }

  if (typeof document.clientWidth == "number") {
     return function () {
       return { width: document.clientWidth, height: document.clientHeight };
     };
  } else if (IS_BODY_ACTING_ROOT || isDocumentElementHeightOff()) {
      var b = document.body;
      return function () {
        return { width: b.clientWidth, height: b.clientHeight };
      };
  } else {
      return function () {
        return { width: docEl.clientWidth, height: docEl.clientHeight };
      };
  }
})();

Note: The dimensions cannot be determined accurately until after the document has finished loading.

from comp.lang.javascript FAQ

This is not a perfect solution, but it is lightweight & suitable for most purposes:

var WX,WY;
if( window.innerWidth )
{
    WX = window.innerWidth;
    WY = window.innerHeight;
} else {
    WX = document.body.clientWidth;
    WY = document.body.clientHeight;
}

For modern browsers:

document.documentElement.clientHeight

is all you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM