js中top、self、parent

1.在应用iframe或者frameset的时候

  parent指的是父窗口。top指的是顶级的窗口。self指的是当前的窗口-window

window.self

 

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

语法:window.self

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

 

window.top

功能:返回顶层窗口,即浏览器窗口。

语法:window.top

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

 

window.parent

功能:返回父窗口。

语法:window.parent

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

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

 

判断当前窗口是否在一个框架中:

<script type="text/javascript">
var b = window.top!=window.self;
document.write( "当前窗口是否在一个框架中:"+b );
</script>

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

 

2.在同一个页面中,使用js获取另一个iframe中的dom元素

  

parent.html
    
        <iframe id="myframe" name="myframe" src="http://localhost:888/child.html" frameborder="3" style="width:300;height:200;">
        </iframe>
        <iframe id="myframe0" src="http://localhost:888/child0.html" frameborder="3" style="width:300;height:200;" name="if2">
        </iframe>

    <script>  
        function init() {
            var obj1 = document.getElementById("myframe");
            console.log(obj1.src);
            //alert(obj1.window.document.myform.username.value);//错误  

            var obj2 = document.frames("myframe"); //获取报错
            console.log(obj2.window.document.myform.username.value);
            //alert(obj2.src);//错误  
        }  
        init()
    </script>

  

child0.html
     child0
    <div id="child0">123</div>

  

child.html
      <form name="myform">
        用户名:
        <input type="text" name="username" value="test" />
    </form>
    <script>
        console.log(parent.frames['if2'].document.getElementById("child0"))
        var b = window.top != window.self;
            document.write("当前窗口是否在一个框架中:" + b);
    </script>

  

转载于:https://www.cnblogs.com/jcxfighting/p/8466278.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值