萬盛學電腦網

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

線上 HTML 編輯器核心原理深度解析:三大技術路線與演進歷程

線上 HTML 編輯器(WYSIWYG)看似神奇,核心原理其實只有三大技術路線。本文從歷史演進角度剖析各路線原理、優缺點、代表產品,並展示最簡原型代碼,幫助你理解「為什麼能在瀏覽器裡像 Word 一樣編輯網頁」。

三大技術路線對照

路線核心 API代表產品/年代優點缺點
1. textarea + 輕量標記 <textarea> + UBB/Markdown 早期論壇 (Discuz!, phpBB)、GitHub Issues、Reddit 極簡、相容性完美、提交直接是純文字、無 XSS 風險 非所見即所得、需預覽切換、複雜排版受限
2. contentEditable (元素級) element.contentEditable = true Medium Editor、早期 CKEditor 3.x、部分 CMS 後台 無需 iframe、DOM 直接操作、輕量 早期 Firefox/IE 行為差異大、選區處理複雜、巢狀編輯區易出 Bug
3. iframe + designMode (文件級) iframe.contentDocument.designMode = 'on' CKEditor 4、TinyMCE 4/5、舊版百度/UEditor、大多數商業編輯器 隔離樣式/腳本不污染主頁、相容性最穩、完整文件結構 (含 head/style) iframe 穿透選取困難、跨域限制、效能較重、回傳內容需額外同步

路線三深度剖析:iframe designMode 運作機制

步驟 1:建立隔離的編輯文件

<iframe id="editor" style="width: 100%; height: 300px; border: 1px solid #ccc;"></iframe>

<script>
const iframe = document.getElementById('editor');
const doc = iframe.contentDocument || iframe.contentWindow.document;

// 必須先寫入完整 HTML 結構,否則 designMode 行為不定
doc.open();
doc.write(`<!DOCTYPE html>
<html><head>
  <meta charset="UTF-8">
  <style>body { font-family: sans-serif; padding: 10px; }</style>
</head><body></body></html>`);
doc.close();

// 關鍵:啟用設計模式
doc.designMode = 'on';

步驟 2:工具列指令映射

// 封裝指令執行
function exec(cmd, arg = null) {
  doc.execCommand(cmd, false, arg);
  iframe.contentWindow.focus(); // 關鍵:執行後焦點會回到主頁,必須強制拉回
}

// UI 綁定範例
document.getElementById('bold').onclick = () => exec('bold');
document.getElementById('italic').onclick = () => exec('italic');
document.getElementById('foreColor').onchange = (e) => exec('foreColor', e.target.value);
document.getElementById('createLink').onclick = () => {
  const url = prompt('請輸入連結:');
  if (url) exec('createLink', url);
};

步驟 3:內容同步與提交

<form action="/save" method="POST">
  <textarea name="content" id="hidden-content" style="display:none;"></textarea>
  <button type="submit">儲存</button>
</form>

<script>
// 提交前同步
document.querySelector('form').addEventListener('submit', () => {
  document.getElementById('hidden-content').value = doc.body.innerHTML;
});

// 或:AJAX 儲存
async function save() {
  const html = doc.body.innerHTML;
  const res = await fetch('/api/save', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ html })
  });
  return res.json();
}

// 從資料庫載入內容
function load(html) {
  doc.body.innerHTML = html;
}

關鍵技術細節:選區與 Range

所有編輯操作本質上都是對 Selection 和 Range 的操作:

// 取得當前選區
const sel = doc.getSelection(); // 標準 API
// 舊 IE: iframe.contentWindow.document.selection.createRange()

// 取得 Range 物件(代表選取範圍)
const range = sel.getRangeAt(0);

// 插入 HTML 的現代寫法(取代 execCommand('insertHTML'))
function insertHTML(html) {
  const sel = doc.getSelection();
  if (sel.rangeCount === 0) return;
  const range = sel.getRangeAt(0);
  range.deleteContents();
  const fragment = range.createContextualFragment(html);
  range.insertNode(fragment);
  // 將游標移到插入內容之後
  range.collapse(false);
  sel.removeAllRanges();
  sel.addRange(range);
}

演進時間軸

  • 1997-2000: IE4 首創 `designMode`、`contentEditable`,Microsoft 獨佔。
  • 2003-2008: Firefox/Mozilla 實作相容 API,FCKeditor (CKEditor 前身)、TinyMCE 崛起,iframe 方案成主流。
  • 2010-2015: HTML5 標準化 `contentEditable`、`Selection`、`Range`、`execCommand`,但行為差異仍大。
  • 2015-至今: execCommand 正式棄用,現代編輯器轉向 ProseMirror、Slate、Lexical、TipTap 等模型驅動架構:
    資料模型 (JSON) ⇄ View (DOM) ⇄ Commands/Transactions,徹底解決選區、巢狀、協同編輯難題。

最簡原型:50 行實現一個迷你編輯器

<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>Mini Editor</title>
<style>
  #toolbar button { margin: 2px; padding: 4px 8px; }
  #editor { width: 100%; height: 300px; border: 1px solid #ccc; }
</style></head><body>
<div id="toolbar">
  <button data-cmd="bold">B</button>
  <button data-cmd="italic">I</button>
  <button data-cmd="underline">U</button>
  <button data-cmd="insertUnorderedList">• 列表</button>
  <button data-cmd="createLink">🔗 連結</button>
  <button onclick="alert(editorDoc.body.innerHTML)">看 HTML</button>
</div>
<iframe id="editor"></iframe>
<script>
const iframe = document.getElementById('editor');
const editorDoc = iframe.contentDocument;
editorDoc.designMode = 'on';
editorDoc.body.style.cssText = 'font-family:sans-serif;padding:10px;';

document.getElementById('toolbar').addEventListener('click', (e) => {
  const btn = e.target.closest('button[data-cmd]');
  if (!btn) return;
  const cmd = btn.dataset.cmd;
  if (cmd === 'createLink') {
    const url = prompt('連結網址:');
    if (url) editorDoc.execCommand(cmd, false, url);
  } else {
    editorDoc.execCommand(cmd);
  }
  iframe.contentWindow.focus();
});
</script></body></html>

理解這三大路線與演進脈絡,不僅能讀懂舊專案代碼,更能在技術選型時,根據專案需求(輕量/重度/協同/行動端)做出最適決策。

copyright © 萬盛學電腦網 all rights reserved