萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

iframe 完整指南:屬性詳解、背景透明化、自適應高度與 JS 動態輸出

1. iframe 基礎屬性速查

屬性值說明HTML5 狀態
srcURL內嵌文檔地址支援
width / heightpx / %寬高支援
name字串框架名稱,供 target 導向支援
frameborder0 / 1是否顯示邊框(建議用 CSS border)已棄用
scrollingyes / no / auto捲軸顯示(建議用 CSS overflow)已棄用
marginwidth / marginheightpx左右/上下邊距(建議用 CSS padding)已棄用
allowtransparencytrue / false允許背景透明(IE 專屬)非標準
sandbox字串安全限制(如 allow-scripts, allow-same-origin)HTML5 新增
loadinglazy / eager延遲載入HTML5 新增

基本範例:

<iframe src="https://example.com" width="100%" height="500" frameborder="0" style="border:none;">
  您的瀏覽器不支援 iframe,請 直接訪問。
</iframe>

2. 背景透明化方案

需雙端配合:

  • 父頁面: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,直接雙端設透明即可。

3. iframe 自適應高度(同域/跨域)

同域方案(父頁可訪問子頁 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)。

4. JS 動態輸出 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 陻塞解析。

5. 避坑清單

  • 安全性:跨域 iframe 預設受同源策略限制,勿在非信任網站嵌入敏感頁面。
  • 效能:iframe 會建立獨立瀏覽上下文,增加記憶體與解析開銷,慎用於列表頁大量嵌入。
  • SEO:搜尋引擎難以索引 iframe 內容,重要內容勿置於 iframe。
  • 廣告攔截:部分瀏覽器/擴充套件會攔截 iframe 廣告,備援方案準備。
copyright © 萬盛學電腦網 all rights reserved