在 CMS、論壇、郵件系統、表單設計器等 Web 應用中,用戶需要所見即所得 (WYSIWYG) 編輯富文本。HTML 在線編輯器(如 eWebEditor、CKEditor、TinyMCE、UEditor)讓不懂 HTML 的用戶也能像用 Word 一樣排版,極大降低了內容創作門檻。
| 方式 | 代碼示例 | 優點 | 缺點 |
|---|---|---|---|
| iframe (推薦) | | 隔離樣式/腳本、跨域友好、標準 HTML5、易於響應式 | 需處理父子頁通信 |
| object (舊 IE 專用) | | IE 早期版本支援較好 | 非標準、僅 IE 支援、安全限制多、已棄用 |
| div contenteditable | | 原生、輕量、無框架開銷 | 需大量 JS 實現工具欄、清理、跨瀏覽器兼容 |
<form id="contentForm" method="post" action="/save">
<iframe id="richeditor" src="/static/editor/editor.html" frameborder="0" style="width:100%; height:400px; border:1px solid #ddd;"></iframe>
<input type="hidden" name="content" id="hiddenContent" />
<button type="submit">保存</button>
</form>
<!DOCTYPE html>
<html><head><meta charset="utf-8"></head><body>
<textarea id="source" style="display:none;"></textarea>
<iframe id="editFrame" style="width:100%; height:100%;"></iframe>
<script>
const editFrame = document.getElementById('editFrame');
editFrame.contentDocument.designMode = 'on'; // 關鍵:開啟設計模式
editFrame.contentDocument.execCommand('styleWithCSS', false, true);
</script>
</body></html>
<script>
// 父頁面:提交前從 iframe 獲取 HTML
document.getElementById('contentForm').onsubmit = function() {
const iframeDoc = document.getElementById('richeditor').contentDocument;
document.getElementById('hiddenContent').value = iframeDoc.body.innerHTML;
return true;
};
// 父頁面:編輯現有內容時回填
function loadContent(html) {
const iframeDoc = document.getElementById('richeditor').contentDocument;
iframeDoc.body.innerHTML = html;
}
</script>
function insertImage(url) {
const iframeDoc = document.getElementById('richeditor').contentDocument;
const img = iframeDoc.createElement('img');
img.src = url;
iframeDoc.execCommand('insertImage', false, url); // 或直接在游標位置插入
}
上傳頁面調用 `window.parent.insertImage(returnedUrl)` 完成插入。
現代 Web 應用嵌入富文本編輯器,**iframe + designMode/contentEditable 是標準路徑**,配合 `postMessage` 或父子頁直接 DOM 訪問實現數據雙向綁定。棄用 `object`/`scriptlet` 等舊技術,擁抱標準、安全、可維護的實現方式。