window.parent、window.top、window.

2018-04-11  本文已影响235人  好吃的野菜

window.top、window.parent、window.self

window.top: 顶层窗口,即最上层的窗口;
window.parent: 父窗口,如果一个窗口没有父窗口,则它的parent属性为自身的引用;
window.self: 当前窗口,即自身的引用;

// 判断当前窗口是否为顶层窗口
if (window.top === window.self) {  // 当前窗口为顶层窗口
}
// 判断当前窗口是子窗口
if (window.parent !== window.self) {   // 当前窗口是子窗口
}

window.frames

window.frameElement

示例代码

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>demo</title>
  <script>
    function isTopWindow() {
        return (window.top === window.self);
    }
    
    function isChildWindow() {
        return (window.parent !== window.self);
    }
    
    function getFrameDomNode1() {
        return window.document.getElementById("iframe_id");
    }
    
    function getFrameDomNode2() {
        var subframes = getWindowFrames();
        return subframes[0].frameElement;
    }
    
    function getWindowFrames() {
        return window.frames;
    }
    
    function getInnerDom1() {
        var frameNode = getFrameDomNode1();
        return frameNode.contentWindow.document;
    }
    
    function getInnerDom2() {
        var frameNode = getFrameDomNode2();
        return frameNode.contentWindow.document;
    }
    
    function getInnerDom3() {
        var subframes = getWindowFrames();
        return subframes[0].document;
    }
    
    window.onload = function () {
        console.info("是否顶级窗口:" + isTopWindow());
        console.info("是否子窗口:" + isChildWindow());
        console.warn("关于frames属性");
        console.info("window.frames === window: " + (window.frames === window));
        console.info("window.frames.length === window.length: " + (window.frames.length === window.length));
        console.warn("关于iframe dom节点");
        console.info("window.iframe_id === window.frames[0] === window.frames['iframe_id']: " + ((window.iframe_id === window.frames[0])    && (window.frames[0] === window.frames['iframe_id'])));
        console.info("两个获取iframe dom 节点结果是否一致:" + (getFrameDomNode1() === getFrameDomNode2()));
        console.info("三个个获取内部 dom 结果是否一致:" + (getInnerDom1() === getInnerDom2()) && (getInnerDom2() === getInnerDom3()));
    }
  </script>
</head>
<body>
<iframe id="iframe_id" width="800" height="300"></iframe>
</body>
</html>

参考资料

  1. MDN web docs
  2. JavaScript 标准参考教程(alpha)
上一篇 下一篇

猜你喜欢

热点阅读