HTML DOM宽度+可见窗口的高度

Ian*_*ink 14 html height dom width

如何在浏览器打开时获取可用空间的当前高度和宽度.

我不想要整个文档的高度,只是屏幕上可见的内容.

Rag*_*geZ 21

您可以查看此博客文章以查看该方法.

简而言之就是给出那个代码

function alertSize() {
    var myWidth = 0, myHeight = 0;
    if(typeof(window.innerWidth) == 'number') {
        // Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } 
    else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        // IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } 
    else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
        // IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }

    window.alert( 'Width = ' + myWidth );
    window.alert( 'Height = ' + myHeight );
}
Run Code Online (Sandbox Code Playgroud)

还需要注意的是,大多数js框架(jquery,ext,prototype)都会提供这样做的功能(恕我直言).

在jQuery中:

$(window).width();
$(window).height();
Run Code Online (Sandbox Code Playgroud)

  • -1 jQuery不返回可见区域的高度和宽度,它返回用户可以滚动到的高度和宽度. (7认同)
  • 我发现了问题和解决方案:要有`$(window).width();`返回可见区域(而不仅仅是`$(document).width();`),确保有在HTML页面的最顶部包含`<!DOCTYPE html>`(或其他正确的`DOCTYPE`). (5认同)

Ken*_*son 5

使用窗口对象属性(内部高度/宽度)来查找网页上内容的尺寸。这包括滚动条。这是一个直观的解释 - > http://goo.gl/L0cBLA

高度:

window.innerHeight
Run Code Online (Sandbox Code Playgroud)

宽度:

window.innerWidth
Run Code Online (Sandbox Code Playgroud)