BOM 之 window 对象

BOM(Browser Object Model)即浏览器对象模型,它为网页程序提供了访问浏览器的能力。但是它没有明确的规范,所以很多实现方式因浏览器而异。

 

window对象表示浏览器窗口的一个实例,它也是ECMAScript标准中定义的Global对象。我们在全局环境中定义的任何变量和对象,都会是window的属性。

 

框架和窗口

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Web Project</title>
</head>
<frameset rows="200,*">
<frame src="topFrame.html" name="topFrame" />
<frameset cols="50%,50%">
<frame src="leftFrame.html" name="leftFrame" />
<frame src="rightFrame.html" name="rightFrame" />
</frameset>
</frameset>
</html>

我们创建了三个框架,第一个是topFrame,第二个是leftFrame,第三个rightFrame。每一个frame都有一个window对象,用于表示当前的框架,每一个框架相当于创建了一个新的窗口。

window对象提供了三个属性用于表示框架之间的关系:

  self:引用当前框架的实例,self就等于当前框架下的window;

  parent:引用当前框架的上一级框架,也就是父框架;

  top:引用最顶层的框架;

如果我们在topFrame.html中用JS访问其他框架:

  console.log( self.name ) // "topFrame" 字符串

  console.log( self.parent ) // Window index.html 对象

  console.log( self.parent.frames.length) // 3

  console.log( self.top === self.parent ) // true

  console.log( self.top.frames[1].name ) // "leftFrame" 字符串

 

窗口位置

各大浏览器并没有一个统一的方式提供窗口位置信息,兼容性的代码如下:

function getScreenPos()

{

  var leftPos = window.screenLeft || window.screenX;

  var rightPos = window.screenTop || window.screenY;

  return [ leftPos, rightPos ];
}

有个地方需要注意:IE中获取的screenTop不是浏览器窗口在屏幕中的y坐标,而是页面可以区域最顶层的位置在屏幕中的y坐标,相当于算上了菜单栏的高度。

两个移动窗口的方法:

  moveTo( x, y ); 窗口移至(x,y)坐标的位置

  moveBy( x, y ); 窗口现有位置加上xhey的偏移量,得到最终位置

 

窗口大小

窗口大小信息同样没有统一的标准,兼容性的代码如下:

function getWindowSize() {

  // FF,chrome,safari,opera
  var pageWidth = window.innerWidth;
  var pageHeight = window.innerHeight;

  // IE
  if ( ! pageWidth ) {
    if ( document.documentElement.clientWidth ) {
      pageWidth = document.documentElement.clientWidth;
      pageHeight = document.documentElement.clientHeight;
    }
    else {
      pageWidth = document.body.clientWidth;
      pageHeight = document.body.clientHeight;
    }
  }

  return [ pageWidth, pageHeight ];
}

同样提供了两个改变窗口大小的函数:resizeTo和resizeBy

 

新建窗口

window.open()方法可以新建一个窗口,接受4个参数:URL,目标窗口(可以是框架名字,也可以是_self,_parent,_top,_blank),设置字符串(用逗号分隔的字符串,表示新建窗口的样式),布尔值(是否取代历史记录)。

该方法返回一个句柄,用于引用新窗口。利用该返回值,我们就可以操作窗口了,比如moveTo,resizeTo,close等等。还有一个opener属性保存打开新窗口的窗口。如果这个返回值是null,则表示新建窗口的功能被屏蔽了。

 

 

 

 

转载于:https://www.cnblogs.com/iRidescent-ZONE/archive/2012/07/07/2580799.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值