一、父级窗口操作iframe里的dom
JS操作iframe里的dom可是使用contentWindow属性,contentWindow属性是指指定的frame或者iframe所在的window对象,
我们知道document对象是window对象的一个子对象,所以我们可以通过document.getElementById(“iframe?ID”).contentWindow.document来获取iframe的document对象,相当于contentDocument属性。
var frame=document.getElementById("frame").contentWindow.document
二、iframe里的js操作父级窗口的dom
iframe里的js要操作父级窗口的dom,必须搞懂几个对象:
parent是父窗口(如果窗口是顶级窗口,那么parent==self==top),
top是最顶级父窗口(有的窗口中套了好几层frameset或者iframe),
self是当前窗口(等价window),
opener是用open方法打开当前窗口的那个窗口;
这样iframe里的js要操作父级窗口的dom可以通过parent,top这些对象来获取父窗口的window对象,例如:
parent.document.getElementById(“dom ID”);
parent,top还能调用父级窗口的的js方法,比如,getIFrameDOM(iID)是父级窗口的一个方法,那么iframe里可以使用parent.getIFrameDOM(“wIframeA”)来调用父级窗口的getIFrameDOM(iID)方法;
dom代码
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body style="margin: 0px">
<span onclick="doFrame()" style="padding: 10px;background: #335263;margin-bottom: 20px"> 设值 </span>
<span onclick="doInnerClick()" style="padding: 10px;background: #335263;margin-bottom: 20px"> 点击 </span>
<input type="text" id="outInput" name="">
<br>
<iframe id="frame" src="frame.html"></iframe>
<script >
function doInnerClick(argument) {
// body...
var frame=document.getElementById("frame").contentWindow.document
var innerBt= frame.getElementById("innerBt")
innerBt.click()
}
function doFrame(argument) {
console.log("doFrame")
var frame=document.getElementById("frame").contentWindow.document
window.inputInner=frame.getElementById("innerInput")
window.inputOut=document.getElementById("outInput")
console.log("inputOut", window.inputOut)
console.log("inputInner", window.inputInner)
console.log("inputInner", window.inputInner.value)
window.inputInner.value="111"
console.log("inputInner", window.inputInner.value)
window.inputInner.style.height="100px"
}
</script>
</body>
</html>
frame.html
···
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body style="margin: 0px;width: 300px;height: 300px;background: red">
<input type="text" id="innerInput" name="">
<input type="button" id="innerBt" onclick="onInnerBtClick()" value="确认"> </span>
<script type="text/javascript">
function onInnerBtClick(argument) {
var innerText=document.getElementById("innerInput")
console.log("innerText",innerText)
console.log("innerText",innerText.value)
console.log("parent",window.parent)
console.log("top",window.top)
}
</script>
</body>
</html>
···
网友评论