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
-
frames属性是一个类似数组的对象;
因为frames实际上是window对象的别名,frames属性又是可以遍历的,所以它是一个类似数组的对象
window.frames.length === window.length
-
frames属性实际上是window对象的别名;
window.frames === window
-
frames属性的每一项是框架内的窗口,即框架内的window对象;
frames属性的每一项并不是iframe的dom节点!!!
若需要获取iframe的dom节点可以通过以下方法:
frames[0].frameElement
window.frameElement
- 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>
网友评论