JavaScript Window - 浏览器对象模型

浏览器对象模型 (BOM)

浏览器对象模型(Browser Object Model (BOM))尚无正式标准。

由于现代浏览器已经(几乎)实现了 JavaScript 交互性方面的相同方法和属性,因此常被认为是 BOM 的方法和属性。

window 对象

浏览器打开一个文档,就创建了一个 window 对象,即 window 对象表示浏览器中打开的窗口。

window 对象是全局对象,可以把窗口的属性作为全局变量来使用。例如,可以只写 document,而不必写 window.document。同样,可以把当前窗口对象的方法当作函数来使用,如只写 alert(),而不必写 Window.alert()。

如果文档包含框架(frame),浏览器会为文档创建一个 window 对象,并为每个框架创建一个额外的 window 对象。

提示:window 对象虽然没有明确的相关标准,但所有浏览器都支持该对象。

HTML DOM 的 document 也是 window 对象的属性之一:

window.document.getElementById("header");

与此相同:

document.getElementById("header");


Window 尺寸

有三种方法能够确定浏览器窗口的尺寸(浏览器的视口,不包括工具栏和滚动条)。

对于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 方案(涵盖所有浏览器):

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<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="浏览器window宽度: " + w + ", 高度: " + h + "。"
</script>
</body>
</html>

其他 Window 方法

一些其他方法:

window.open() - 打开新窗口

window.close() - 关闭当前窗口

window.moveTo() - 移动当前窗口

window.resizeTo() - 调整当前窗口的尺寸


继续学习
||
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script type="text/javascript"> myWindow=window.open('','','width=200,height=100') myWindow.document.write("This is 'myWindow'") myWindow.moveTo(0,0) </script> </head> <body> <p>把新窗口移动到指定屏幕左上角(屏幕左上角为 0,0 坐标,往右和下计算为正)</p> </body> </html>
提交重置代码
章节
笔记
提问
课件
反馈
捐赠

JavaScript学习指南