这是我参与11月更文挑战的第16天,活动详情查看:2021最后一次更文挑战
BOM 的核心对象是 window,表示浏览器的一个实例。它是通过 JavaScript 访问浏览器的一个接口,又是 Global 对象。任何一个对象、变量和函数都可以访问。
全局作用域
在全局作用域中声明的变量、函数都会变成 window 对象的属性和方法。
var sex = '男';
function getSex() {
console.log(this.sex);
}
console.log(window.sex);
window.getSex();
窗口关系及框架
每个框架都拥有自己的 window 对象,保存在 frames 集合中。通过索引或者框架名访问 window 对象。
<iframe src="topiframe.html" name="topFrame" frameborder="0"></iframe>
<iframe src="bottomiframe.html" name="bottomFrame" frameborder="0"></iframe>
上面的例子可以通过 window.frames[0] 或者 window.frames["topFrame"] 引用框架,最好使用 top 而非 window 引用,如 top.frames[0]。
另一个 window 对象是 parent,parent 对象始终指向当前框架的直接上层框架。
窗口位置
用于表示窗口相对于屏幕左边和上边的位置,IE、Safari、Opera 和 Chrome 提供了 screenLeft 和 screenTop 属性,Firefox 提供了 screenX 和 screenY。
var leftPos = (typeof window.screenLeft == "number") ? window.screenLeft : window.screenX;
var topPos = (typeof window.screenTop == "number") ? window.screenTop : window.screenY;
窗口大小
浏览器提供了4个属性来确定一个窗口的大小:innerWidth、innerHeight、outerWidth、outerHeight。
| IE9+、Safari、Firefox | outerWidth 和 outerHeight 返回浏览器窗口本身的尺寸 |
| Opera | outerWidth 和 outerHeight 表示页面视图容器的大小,innerWidth 和 innerHeight 表示该容器中页面视图区的大小(减去边框宽度) |
| chrome | 4个属性返回相同的值,即视口大小而非浏览器窗口大小 |
| IE、Safari、Firefox、Opera、Chrome | document.documentElement.clientWidth 和 document.documentElement.clientHeight 保存了页面视口的信息 |
IE6中,需要在标准模式下有效;混杂模式通过 document.body.clientWidth 和 documet.body.clientHeight 取得相同信息 |
var pageWidth = window.innerWidth;
var pageHeight = window.innerHeight;
if (typeof pageWidth != "number") {
if (document.compatMode == "CSS1Compat") {
pageWidth = document.documentElement.clientWidth;
pageHeight = document.documentElement.clientHei
} else {
pageWidth = document.body.clientWidth;
pageHeight = document.body.clientHeight;
}
}
resizeTo() 和 resizeBy() 可以调整浏览器窗口的大小,resizeTo() 接收浏览器窗口的新宽度和新高度参数,resizeBy() 接收新窗口与原窗口的宽度和高度之差。
window.resizeTo(100, 100); // 调整至 100*100
widow.resizeBy(150, 100); // 调整至 250*200
两个方法有可能被浏览器禁用,不适用于框架,只能对最外层的 window 对象使用