JavaScript 操作 iframe 中的Dom

<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),就不會有這種問題。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章