<iframe id="iframe" name="framename" src="mainpage.html" frameborder="0" scrolling="no" width="100%"></iframe>
1、使用 iframe.contentWindow.document 在父窗口中获取子窗口中的Dom
var iframe = document.getElementById('iframe');
iframe.contentWindow.document.getElementById("xx").style.backgroundColor="#f00";
2、使用 parent.document 在子窗口中获取父窗口的Dom
如:
parent.document.getElementById('text').style.color="#fff";
子窗口之间的DOM获取,可以一步步向上先找到其共同的祖先,再一步步向下获取到需要的iframe的DOM。
3、每个iframe都有一个window对象,并且保存在frames集合中,可以通过数值索引或者iframe名称来访问相应的window对象。
frames["framename"].document.getElementById("xx").style.backgroundColor="#f00";
frames[1].document.getElementById("xx").style.backgroundColor="#f00";
注:此时,在本地用绝对路径直接运行HTML文件(如 file:///D:/code/TinyHeart/index.html),会报错
Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.
这是因为,不同文件中的操作是按照跨域处理的,在编辑器中按照网站打开项目(http://localhost:63342/TinyHeart/index.html),就不会有这种问题。