最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get the available browser window size (clientHeightclientWidth) consistently across multiple browsers - Stack Overf

programmeradmin6浏览0评论

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.

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.

Share Improve this question asked Feb 12, 2011 at 7:32 user193476user193476 1
  • Well, third party libraries are excellent for reducing development for things like this, which shouldn't take a long time, but it does since JavaScript isn't consistent across all browsers :p I recommend opening up jQuery or Mootools and checking the code it uses (presumably it is safe, cross-browser compatible JavaScript) – Andrew Jackman Commented Feb 12, 2011 at 7:41
Add a comment  | 

3 Answers 3

Reset to default 9

For modern browsers:

document.documentElement.clientHeight

is all you need.

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论