異於傳統 <frameset> 必須佔據整個視窗,<iframe> 可嵌入任意頁面位置,獨立捲動、獨立載入、不影響主頁面歷史記錄,適合:廣告輪播、地圖嵌入、第三方 Widget、單頁應用局部更新、舊系統整合。
<!doctype html public "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>iframe 框架應用</title>
<style type="text/css">
body, td, th { font-size: 12px; }
body { margin: 0; }
a { font-size: 12px; }
</style>
</head>
<body>
<div class="title">
<a href="/" target="iframea">標題文檔</a>
<a href="b" target="iframea">標題文檔</a>
<a href="c" target="iframea">標題文檔</a>
</div>
<iframe scrolling="no" name="iframea" height="300"></iframe>
</body>
</html>
| 屬性 | 值 | 說明 |
|---|---|---|
| name | iframea | 命名框架,供 target 導向 |
| src | (範例未設) | 初始載入頁面,可由 JS 動態設定 |
| scrolling | no/yes/auto | 捲軸顯示策略,範例強制關閉 |
| height | 300 | 固定高度 300px,寬度預設 100% |
| frameborder | (未設,預設 1) | HTML5 建議用 CSS border: none; |
| target="iframea" | 連結屬性 | 點擊連結在指定 iframe 中載入 |
document.getElementById('myIframe').src = 'new-page.html';postMessage API 實現父頁面與 iframe 雙向資料傳遞(需同源或設定 allow 屬性)。sandbox="allow-scripts allow-same-origin allow-forms" 限制 iframe 權限,防止惡意腳本執行。iframe.contentWindow.document.body.scrollHeight 動態調整高度,消除雙捲軸。loading="lazy" (HTML5) 或 IntersectionObserver 觸發 src 設定,提升首屏速度。<noframes> 降級內容或 <a href="..."> 直接連結給無法支援 iframe 的用戶/爬蟲。title 屬性描述 iframe 用途(如 title="主內容區")。