iframe 嵌入頁面時,父子文檔間的元素選取與操作是常見需求。本文系統整理**原生 DOM**、**jQuery 選擇器**、**.contents()** 等多種獲取 iframe 內部元素的方法,並針對同域/跨域場景給出最佳實踐。
| 方向 | 原生 DOM | jQuery 封裝 |
|---|---|---|
| 父 → 子 | window.frames["name"].documentiframeEl.contentWindow.documentiframeEl.contentDocument (IE8+) | $(window.frames["name"].document).find(...)$("iframe").contents().find(...) |
| 子 → 父 | window.parent.documentwindow.top.document | $(window.parent.document).find(...) |
// 方式 A:window.frames
$(window.frames["iframeSon"].document).find(":text");
// 方式 B:.contents() (推薦,鏈式調用)
$("#iframeSon").contents().find(":text");
// 方式 C:原生 document 後包裹
$(document.getElementById('iframeSon').contentWindow.document.body).html();
$(window.parent.document).find("input[type='radio']").prop("checked", true);
// 多種等價寫法
$(window.frames["iframe1"].document).find("#testId").html();
$("#iframe1").contents().find("#testId").html();
$("iframe[name='iframe1']").contents().find("#testId").val();
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<script src="js/jquery-1.2.6.js"></script>
<script>
$(function(){
// 示例:父頁面修改子 iframe 中 id="d1" 的顏色
$("#iframe1").contents().find("#d1").css('color', 'red');
// 示例:父頁面修改子 iframe 中 name="t1" 的輸入框背景
$(window.frames["iframe1"].document).find("input[name='t1']").css({background: "#369"});
// 示例:動態修改 iframe src
// $("#iframe1").attr("src", "newpage.html"); // 此處 .src() 非標準,應用 .attr()
});
</script>
</head>
<body>
<input id="t1" />
<iframe id="iframe1" src="child.htm"></iframe>
<iframe height="100" src="child.htm" width="300"></iframe>
</body>
</html>
document.domain = 'base.com'(僅限主域相同,且**已被標準廢棄**,現代瀏覽器漸漸移除支援)。window.postMessage 進行消息傳遞。
// 父頁面發送
iframe.contentWindow.postMessage({action: 'getData', id: 1}, 'https://child.com');
// 子頁面監聽
window.addEventListener('message', e => {
if (e.origin !== 'https://parent.com') return;
if (e.data.action === 'getData') {
e.source.postMessage({result: 'data'}, e.origin);
}
});
iframe.onload 後才能安全訪問 .contents(),否則文檔未就緒報錯。.prop() 替代 .attr() 設置 checked/disabled 等布爾屬性。input[@type='radio'] 為 jQuery 1.2 舊語法,**現代版本請用 input[type='radio']** (去掉 @)。.contentWindow 穿透,極易出錯,建議扁平化架構。qiankun, Module Federation) 替代 iframe 嵌入應用。postMessage 通信 SDK。熟練掌握 iframe DOM 穿透技巧是維護老系統必備技能,新架構設計應盡量避免 iframe 帶來的樣式隔離、通信複雜、SEO 不利等問題。