javascript关于Iframe父窗口和子窗口交互

//兼容IE、Firefox的iframe DOM获取函数
function getIFrameDOM(id){
	return document.getElementById(id).contentDocument || document.frames[id].document;
}


parent.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

</head>
<body>
<div id="pHello" style="margin:10px auto;width:360px;height:30px;">此处可通过iframeB的JavaScript函数,来替换哦~</div>
<iframe id="wIframeA" name="myiframeA" src="a.html" scrolling="no" frameborder="1"></iframe>
<iframe id="wIframeB" name="myiframeB" src="b.html" scrolling="no" frameborder="1"></iframe>
<div style="margin:10px auto;width:300px;height:40px;">
<input type="button" value="父窗口操作iframeA" onclick="iframeA();" style="width:150px;float:left;"/>
<input type="button" value="父窗口操作iframeB" onclick="iframeB();" style="width:150px;float:left;"/>
</div>
<script type="text/javascript">
function iframeA(){
	var a = getIFrameDOM("wIframeA");
	a.getElementById('hello_a').style.background = "red";
}
function iframeB(){
	var a = getIFrameDOM("wIframeB");
	a.getElementById('hello_b').style.background = "green";
}
function getIFrameDOM(id){
	return document.getElementById(id).contentDocument || document.frames[id].document;
}
</script>
</body>
</html>

a.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

</head>
<body>
<div id="hello_a">Hello a.html</div>
<script>
	
</script>
</body>
</html>

b.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div id="hello_b">Hello b.html</div>
<input type="button" value="子窗口操作父窗口" onclick="parentIframe();" style="width:150px;float:left;"/>
<input type="button" value="子窗口操作iframeA" onclick="iframeA();" style="width:150px;float:left;"/>
<script type="text/javascript">
function iframeA(){
	var a = parent.getIFrameDOM("wIframeA");
	a.getElementById('hello_a').style.background = "blue";
}
function parentIframe(){
	parent.document.getElementById("pHello").innerHTML = "<p style='background:#000;color:#fff;font-size:15px;'>O(∩_∩)O哈哈~用子窗口B就可以替换你!不服吗?</p>";
}
</script>
</body>
</html>

注意:

--------------------------------------------

在firefox下,iframe背景默认的是透明的,在IE下默认不是透明的,

我们可以使用allowTransparency='true' 来设置IE下的iframe为透明,

另外我们使用scrolling ='no' frameborder='0'分别来实现iframe页面没有滚动条,边框宽度。


动态将Iframe背景置为透明

iframeObj.allowTransparency = true;

你可能感兴趣的:(JavaScript,iframe,XHTML,function,firefox,button)