海南网站运营托管咨询国际外贸网络交易平台
1、iframe.contentWindow(主页面调用iframe)
此处的iframe是从document取得的,即作作为document的子对象出现,虽然是文档(document)对象,但由于它是独立的页面,因而拥有自己的事件,拥有自己的窗口对象(contentWindow);contentWindow属性是指指定的frame或者iframe所在的window对象。
在IE中iframe或者frame的contentWindow属性可以省略,但在Firefox中如果要对iframe对象进行编辑则必须指定contentWindow属性。
先获取iframe里面的window对象,
var iframe = document.getElementById('myFrame').contentWindow// 在IE下
var iframe = document.frames['myFrame']
再通过这个对象,获取到里面的DOM元素
var input = iframe.document.getElementById('test')
在主页面,操作iframe里面的DOM元素实例如下:
// a.html页面
<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>iframe.contentWindow</title><script type="text/javascript">function getValue() {var tmp = '';if(document.frames) {tmp += document.frames['myFrame'].document.getElementById('test').value;} else {tmp = document.getElementById('myFrame').contentWindow.document.getElementById('test').value;}if(confirm(tmp)) {location.href = tmp.split(':')[1]}}</script></head><body onload="getValue()"><iframe id="myFrame" src='b.html' width="600px" height="100px;"></iframe></body>
</html>
b.html页面
// b.html页面
<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>iframe</title><style>#test {border: solid royalblue 2px;border-radius: 4px;width: 500px;color: #797979;height: 50px;line-height: 50px;font-size: 20px;}</style></head><body><input type='text' id="test" value='欢迎访问:http://blog.csdn.net/qq_27626333'></body>
</html>
2、window.parent(iframe页面调用主页面)
在iframe本页面,要操作这个iframe的父页面的DOM元素(即嵌套这个iframe的页面)可以用:window.parent、window.top(这里的TOP是获取的顶层,即有多层嵌套iframe的时候使用)
// a.html页面
<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>iframe.contentWindow</title><script type="text/javascript">function parentValue() {if(confirm('欢迎访问:http://blog.csdn.net/qq_27626333')) {location.href = 'http://blog.csdn.net/qq_27626333'}}</script></head><body><iframe id="myFrame" src='b.html' width="510px" height="150px;"></iframe></body>
</html>
// b.html页面
<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>iframe</title><style>.contain {display: flex;flex-direction: column;width: 500px;}#test {border: solid royalblue 2px;border-radius: 4px;width: 100%;color: #797979;height: 50px;line-height: 50px;font-size: 20px;}#button {border: solid #20A0FF 2px;border-radius: 4px;margin: 20px auto;padding: 10px;background-color: #20A0FF;color: white;}</style><script>function parentValue() {window.parent.parentValue()}</script></head><body><div class="contain"><input type='text' id="test" value='欢迎访问:http://blog.csdn.net/qq_27626333'><input type="button" id="button" value="调用主页面方法" onclick="parentValue()"/></div></body>
</html>