使用JavaScript可以方便的进行iframe的DOM操作
若是在本地测试,可直接使用IE和FireFox,使用chrome则需要执行chrome --disable-web-security
禁用chrome的WEB安全限制则可以在本地进行测试,代码如下:
iframe_dom.html
<!DOCTYPE html">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>iframe DOM操作[demo]|使用JavaScript来进行iframe的DOM操作 |by WYQ</title>
<style type="text/css">
body {
margin: 0;
padding: 0;
}
#wIframeA,#wIframeB {
width: 400px;
height: 400px;
float: left;
}
</style>
</head>
<body>
<h1 style="text-align: center">
使用JavaScript在IE和Firefox下进行iframe的DOM操作[demo]
</h1>
<div style="margin: 10px auto; width: 300px; height: 40px;">
<input type="button" value="父窗口操作iframeA" οnclick="iframeA();"
style="width: 150px; float: left;" />
<input type="button" value="父窗口操作iframeB" οnclick="iframeB();"
style="width: 150px; float: left;" />
</div>
<div id="pHello"
style="margin: 10px auto; width: 360px; height: 30px;">
此处可通过iframeB的JavaScript函数,来替换哦~
</div>
<div style="margin: 10px auto; width: 810px; height: 300px;">
<iframe id="wIframeA" name="myiframeA" src="a.html" scrolling="no"
frameborder="0"></iframe>
<iframe id="wIframeB" name="myiframeB" src="b.html" scrolling="no"
frameborder="0"></iframe>
</div>
<script type="text/javascript">
function iframeA() {
var a = getIFrameDOM("wIframeA");
a.getElementById('hello').style.background = "red";
}
function iframeB() {
var a = getIFrameDOM("wIframeB");
a.getElementById('hello').style.background = "green";
}
function getIFrameDOM(id) {
return document.getElementById(id).contentDocument
|| document.frames[id].document;
}
</script>
</body>
</html>
a.html
<!DOCTYPE html">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>iframe DOM操作 _iframeA|by WYQ</title>
</head>
<body>
<h1>I am iframe A</h1>
<p id="hello">Hello World!</p>
</body>
</html>
b.html
<!DOCTYPE html">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>iframe DOM操作 _iframeB|by WYQ</title>
</head>
<body>
<h1>I am iframe B</h1>
<p id="hello">Hello World!</p>
<button οnclick="child4parent();" style="width:180px;float:left;">iframeB子窗口操作父窗口</button>
<button οnclick="child4child();" style="width:150px;float:left;">iframeB操作子窗口A</button>
<script type="text/javascript">
function child4child(){
var a=parent.getIFrameDOM("wIframeA");
a.getElementById('hello').innerHTML="<span style='color:blue;font-size:18px;background:yellow;'>看,俺子窗口B也能DOM你A!</span>";
}
function child4parent(){
parent.document.getElementById("pHello").innerHTML="<p style='background:#000;color:#fff;font-size:15px;'>O(∩_∩)O哈哈~用子窗口B就可以替换你!不服吗?</p>";
}
</script>
</body>
</html>