**只有同源(協議、域名、端口相同)的 iframe 才能互相訪問 DOM**。跨域需用 postMessage。
// 方法一:contentWindow.document (推薦,標準)
function getIframeDoc(iframeId) {
return document.getElementById(iframeId).contentWindow.document;
}
// 使用
getIframeDoc('frameA').getElementById('ooxx').style.backgroundColor = '#f00';
// 方法二:window.frames['name'] (僅能訪問 window 對象,不可直接查元素)
// window.frames['iframeA'].document.getElementById('ooxx') // 同源下可行
// 必須通過 window.frames 或 contentWindow
window.frames['iframeB'].getsFun();
// 或
document.getElementById('frameB').contentWindow.getsFun();
// a.html 中
// 訪問父頁面元素
parent.document.getElementById('pox').style.color = '#fff';
// 調用父頁面方法
parent.testP('參數');
// 獲取父頁面變量
var val = parent.someVariable;
// b.html 訪問 a.html
// 方式一:父頁面暴露獲取 iframe 文檔的方法
var aDoc = parent.getIframe('frameA'); // 父頁面定義的函數
aDoc.getElementById('divooxx').style.backgroundColor = '#000';
// 方式二:直接通過父頁面 frames 集合
parent.frames['frameA'].testBA(); // 調用 a.html 的方法
<iframe src="a.html" id="frameA" name="frameA"></iframe>
<iframe src="b.html" id="frameB" name="frameB"></iframe>
<script>
function getIframe(id) {
return document.getElementById(id).contentWindow.document;
}
function testP(msg) { alert('父頁面收到:' + msg); }
</script>
<div id="ooxx">A的元素</div>
<div id="divooxx">供B訪問</div>
<button onclick="parent.testP('來自A')">調用父方法</button>
<script>
function testBA() { alert('A的方法被B調用'); }
</script>
<button onclick="visitSibling()">訪問A的元素</button>
<button onclick="callSiblingMethod()">調用A的方法</button>
<script>
function visitSibling() {
var doc = parent.getIframe('frameA');
doc.getElementById('divooxx').style.color = 'red';
}
function callSiblingMethod() {
parent.frames['frameA'].testBA();
}
</script>
// 父頁面
window.addEventListener('message', function(e) {
if (e.origin !== 'https://child-domain.com') return;
console.log('收到子頁面消息:', e.data);
});
// 子頁面
parent.postMessage({ type: 'resize', height: 500 }, 'https://parent-domain.com');
iframe.contentWindow.document 獲取文檔對象。iframe.contentWindow.fn() 或 window.frames[name].fn()。parent 訪問父頁面,top 訪問頂層窗口。onload 後再操作。document.domain 降級同源(已棄用/受限)。