js 获取浏览器宽度和高度

来源:互联网 发布:知乎 北上广深 编辑:程序博客网 时间:2024/05/01 16:18
有三种方法能够确定浏览器窗口的尺寸(浏览器的视口,不包括工具栏和滚动条

)。

对于Internet Explorer、Chrome、Firefox、Opera 以及 Safari:

    window.innerHeight - 浏览器窗口的内部高度
    window.innerWidth - 浏览器窗口的内部宽度

对于 Internet Explorer 8、7、6、5:

    document.documentElement.clientHeight
    document.documentElement.clientWidth

或者

    document.body.clientHeight
    document.body.clientWidth

实用的 JavaScript 方案(涵盖所有浏览器):

var w=window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var h=window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

---------------------完整的例子---------------------
<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var w=window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var h=window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

x=document.getElementById("demo");
x.innerHTML="浏览器的内部窗口宽度:" + w + ",高度:" + h + "。"
</script>

</body>
</html>
注:所有 JavaScript 全局对象、函数以及变量均自动成为 window 对象的成员。其他 Window 方法:

    window.open() - 打开新窗口
    window.close() - 关闭当前窗口
    window.moveTo() - 移动当前窗口
    window.resizeTo() - 调整当前窗口的尺寸
0 0
原创粉丝点击