代码之家  ›  专栏  ›  技术社区  ›  Yo Momma

获取窗口高度

  •  32
  • Yo Momma  · 技术社区  · 15 年前

    这让我很沮丧。它应该非常简单,但我不能让它在IE中工作。我想得到当前窗口的高度:不是滚动高度,不是文档高度,而是实际的窗口高度。我试过了 window.innerHeight 哪些回报 undefined document.documentElement.clientHeight 它给出了卷轴的高度。

    3 回复  |  直到 7 年前
        1
  •  73
  •   mikemaccana    7 年前

    对于当前浏览器

    window.innerHeight 
    

    对于IE 8及更低版本,使用

    document.documentElement.offsetHeight;
    

    如果需要较旧的浏览器,请使用:

    var height = "innerHeight" in window 
                   ? window.innerHeight
                   : document.documentElement.offsetHeight; 
    
        2
  •  5
  •   TechAurelian    12 年前

    我正在使用:

    doc = document;
    var theHeight = Math.max(
        doc.body.scrollHeight, doc.documentElement.scrollHeight,
        doc.body.offsetHeight, doc.documentElement.offsetHeight,
        doc.body.clientHeight, doc.documentElement.clientHeight
    );
    

    在这里找到: Get document height (cross-browser) - James Padolsey

    同时也发现 jQuery 做同样的事情:

    // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
    // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
    return Math.max(
      elem.body[ "scroll" + name ], doc[ "scroll" + name ],
      elem.body[ "offset" + name ], doc[ "offset" + name ],
      doc[ "client" + name ]
    );
    
        3
  •  1
  •   pakore    15 年前

    http://www.javascripter.net/faq/browserw.htm

    请注意,使用的代码 document.body.offsetWidth document.body.offsetHeight 必须在浏览器分析标记后执行。

    更新: 试试这个

    <script type="text/javascript">
    <!--
    
     var viewportwidth;
     var viewportheight;
    
     // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
    
     if (typeof window.innerWidth != 'undefined')
     {
          viewportwidth = window.innerWidth,
          viewportheight = window.innerHeight
     }
    
    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
    
     else if (typeof document.documentElement != 'undefined'
         && typeof document.documentElement.clientWidth !=
         'undefined' && document.documentElement.clientWidth != 0)
     {
           viewportwidth = document.documentElement.clientWidth,
           viewportheight = document.documentElement.clientHeight
     }
    
     // older versions of IE
    
     else
     {
           viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
           viewportheight = document.getElementsByTagName('body')[0].clientHeight
     }
    document.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');
    //-->
    </script>
    

    发现 here