| 屬性 | 值 | 說明 | HTML5 狀態 |
|---|---|---|---|
| src | URL | 內嵌文檔地址 | 支援 |
| width / height | px / % | 寬高 | 支援 |
| name | 字串 | 框架名稱,供 target 導向 | 支援 |
| frameborder | 0 / 1 | 是否顯示邊框(建議用 CSS border) | 已棄用 |
| scrolling | yes / no / auto | 捲軸顯示(建議用 CSS overflow) | 已棄用 |
| marginwidth / marginheight | px | 左右/上下邊距(建議用 CSS padding) | 已棄用 |
| allowtransparency | true / false | 允許背景透明(IE 專屬) | 非標準 |
| sandbox | 字串 | 安全限制(如 allow-scripts, allow-same-origin) | HTML5 新增 |
| loading | lazy / eager | 延遲載入 | HTML5 新增 |
基本範例:
<iframe src="https://example.com" width="100%" height="500" frameborder="0" style="border:none;">
您的瀏覽器不支援 iframe,請 直接訪問。
</iframe>
需雙端配合:
allowtransparency="true" style="background:transparent;"<body style="background:transparent;"> 或 CSS body { background: transparent; }<!-- 1. 透明生效 -->
<iframe id="f1" src="transparentBody.htm" allowtransparency="true"></iframe>
<!-- 2. 父頁指定綠色,子頁透明 → 顯示綠色 -->
<iframe id="f2" src="transparentBody.htm" allowtransparency="true" style="background:green;"></iframe>
<!-- 3. 無 allowtransparency,子頁透明 → 白底(預設) -->
<iframe id="f3" src="transparentBody.htm"></iframe>
<!-- 4. 無 allowtransparency,父頁綠色 → 白底蓋住綠色 -->
<iframe id="f4" src="transparentBody.htm" style="background:green;"></iframe>
結論:allowtransparency="true" + 子頁 background:transparent 為核心。現代瀏覽器多無需 allowtransparency,直接雙端設透明即可。
同域方案(父頁可訪問子頁 DOM):
// 父頁
function resizeIframe(iframe) {
try {
iframe.style.height = iframe.contentWindow.document.documentElement.scrollHeight + 'px';
} catch (e) { console.warn('跨域或載入中', e); }
}
window.addEventListener('message', e => {
if (e.data.type === 'iframeResize') {
document.getElementById(e.data.id).style.height = e.data.height + 'px';
}
});
// 子頁(同域可直接調用 parent.resizeIframe;跨域用 postMessage)
// 同域
parent.resizeIframe(window.frameElement);
// 跨域
window.parent.postMessage({ type: 'iframeResize', id: 'myIframe', height: document.body.scrollHeight }, '*');
第三方庫推薦:iframe-resizer(自動處理跨域、重繪、多 iframe)。
document.write(
'<iframe align="middle" marginwidth="0" marginheight="0" ' +
'src="https://img.example.com/ads/468_1.htm" ' +
'frameborder="0" scrolling="no" width="660" height="80"></iframe>'
);
現代替代:使用 document.createElement('iframe') + appendChild,避免 document.write 陻塞解析。