在多个浏览器中一致地获取可用的浏览器窗口大小(clientHeight/clientWidth)

5 javascript browser

我想要一种在 使用jQuery/Mootools /任何第三方库依赖项的情况下在多个浏览器中获取可用窗口大小的方法.我已经对此做了一些研究,但我遇到的一半事情都在谈论Netscape Navigator ......

只是想知道那里的人是否有更多的近期建议.

gbl*_*zex 5

用法

var width = getWindowSize().width;
Run Code Online (Sandbox Code Playgroud)

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 };
      };
  }
})();
Run Code Online (Sandbox Code Playgroud)

注意:在文档加载完成之前,无法准确确定尺寸。

来自 comp.lang.javascript常见问题解答


Ste*_*hon 5

对于现代浏览器:

document.documentElement.clientHeight
Run Code Online (Sandbox Code Playgroud)

是你所需要的全部。