您的位置:首页 > Web前端 > JavaScript

Js中的window.parent ,window.top,window.self 详解

2017-10-10 10:53 573 查看
在应用有frameset或者iframe的页面时,parent是父窗口,top是最顶级父窗口(有的窗口中套了好几层frameset或者iframe),self是当前窗口, opener是用open方法打开当前窗口的那个窗口。

window.self:是对当前窗口自身的引用。它和window属性是等价的。

注:window、self、window.self是等价的。

window.top:返回顶层窗口,即浏览器窗口。

注:如果窗口本身就是顶层窗口,top属性返回的是对自身的引用。

window.parent:返回父窗口。

注:如果窗口本身是顶层窗口,parent属性返回的是对自身的引用。

在框架网页中,一般父窗口就是顶层窗口,但如果框架中还有框架,父窗口和顶层窗口就不一定相同了。

我们在平时应用中,为了防止别人将我们自己的网页用iframe的方式嵌入到其它网页中去,我们一般这样:

这是我们的网页1.html

<script language="javascript">

if(top !== self){

top.location.href = location.href;
}

</script>

<input type=button name=name value="网页1的botton按钮" >


别人通过frameset方式将1.html嵌入到其他网页中

<frameset COLS="150,*">
<frame src="1.html" name=top>
</frameset>


解析:top指向最顶层窗口的window对象,self指向当前窗口的window对象。如果网页中没有iframe,则top和self是同一个值,而当我们的网页嵌入到firame中时,则top和self不相同,此时将执行 top.location.href = location.href ,即网页会重新加载,使得当前网页1.html为顶层网页。这样就能有效地防止网页被引用在别人的页面中。

我们可以将框架视为窗口中的不同区域,框架是浏览器窗口中特定的部分。一个浏览器窗口可以根据你的需要分成任意多的框架,一个单个的框架也可以分成其它多个框架,即所谓的嵌套框架。

<frameset cols="150,*">
<frame src="left.htm" name=left>
<frameset rows="150,*">
<frame src="1.html" name=aa>
<frame src="2.html" name=bb>
</frameset>
</frameset>


parent与opener的区别:

parent指父窗口,在frameset中,frame的parent就是frameset窗口。

opener指用window.open方式创建的新窗口对应的原窗口。

parent是相对于框架来说父窗口对象。

opener是针对于用window.open打开的窗口来说的父窗口,前提是window.open打开的才有。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息