来源: 吾推网  发布时间: 2017-11-02   次浏览
1.通过js操作子级里面的元素变化。
html部分:
 <h4>我是最顶级父topIframe</h4>
 <button id="btn1">
   点击我改变子级pIframe1的背景色
 </button><br/><br/>
 <iframe id="topIframe" src="iframeChild.html"></iframe>
 <iframe id="topIframe2" src="iframeChild2.html"></iframe>
 js部分:
 var btn=document.getElementById('btn1');
 btn.onclick=function(){
 var childBody=document.getElementById("topIframe").contentWindow.document.getElementsByTagName('body')[0];
     childBody.style.backgroundColor="#ff0"; 
 }
2.子级iframe操作父级元素。
html部分:
 我是topIframe的子级pIframe1
 <button id="pBtn">点击我改变topIframe的标题颜色</button>
js部分:
 var btn=document.getElementById('pBtn');
 btn.onclick=function(){
//操作父级用window.parent
//操作父级的父级用window.parent.parent以此类推
//操作最顶级可以用window.top
var parent=window.parent;
var tit=parent.document.getElementsByTagName('h4')[0];
tit.style.color='#f00';
 }
3.子级iframe操作父级元素里面的某个iframe的元素变化
相当于操作兄弟iframe里面的元素变化。

html部分:
 我是topIframe的子级pIframe1
 <button id="pBtn2">点击我改变父级中pIframe2的背景颜色</button>
js部分:
 var btn2=document.getElementById('pBtn2');
 btn2.onclick=function(){
//先获取到父级
var parent=window.parent;
//然后找到父级中对应的兄弟iframe
var topCont=parent.document.getElementById("topIframe2").contentWindow;
var body=topCont.document.getElementsByTagName('body')[0];
     body.style.backgroundColor='#f00';
 }