萬盛學電腦網

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

JavaScript 動態切換 HTML 標籤技巧:標籤轉換、元件替換與安全淨化策略

標籤切換的典型應用場景

  • 富文本編輯器:<b> ↔ <strong>、<i> ↔ <em>
  • Markdown 渲染後處理:標題層級調整、程式碼區塊包裝
  • 舊系統遷移:<font> → <span class>、<center> → <div style="text-align:center">
  • 元件庫升級:<old-button> → <new-button>
  • A/B 測試:動態替換整個區塊結構

方案一:DOM 遍歷替換(保留事件、引用、狀態)

function swapTags(root, tagMap, options = {}) {
  // tagMap: { 'old-tag': 'new-tag', 'b': 'strong' }
  const walker = document.createTreeWalker(
    root,
    NodeFilter.SHOW_ELEMENT,
    {
      acceptNode: node => {
        const newTag = tagMap[node.tagName.toLowerCase()];
        return newTag ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
      }
    }
  );

  const toReplace = [];
  while (walker.nextNode()) toReplace.push(walker.currentNode);

  toReplace.forEach(oldEl => {
    const newTag = tagMap[oldEl.tagName.toLowerCase()];
    const newEl = document.createElement(newTag);
    
    // 複製屬性(可選過濾)
    [...oldEl.attributes].forEach(attr => {
      if (!options.excludeAttrs?.includes(attr.name)) {
        newEl.setAttribute(attr.name, attr.value);
      }
    });
    
    // 移動子節點(保留事件監聽器、文字節點身分)
    while (oldEl.firstChild) {
      newEl.appendChild(oldEl.firstChild);
    }
    
    // 替換
    oldEl.parentNode.replaceChild(newEl, oldEl);
    
    // 回調
    options.onReplace?.(oldEl, newEl);
  });
}

// 使用範例
swapTags(document.querySelector('.content'), {
  'b': 'strong',
  'i': 'em',
  'font': 'span',  // 遷移 font 標籤
  'center': 'div'  // 遷移 center 標籤
}, {
  excludeAttrs: ['style'], // 不複製內聯樣式,改用 CSS 類別
  onReplace: (oldEl, newEl) => {
    if (oldEl.tagName === 'FONT') {
      // 轉換 font 屬性到 style/class
      const size = oldEl.getAttribute('size');
      if (size) newEl.style.fontSize = `${parseInt(size) * 3}px`; // 近似換算
    }
  }
});

方案二:innerHTML 字串替換(簡單但破壞狀態)

function swapTagsHTML(container, tagMap) {
  let html = container.innerHTML;
  Object.entries(tagMap).forEach(([oldTag, newTag]) => {
    const regexOpen = new RegExp(`<${oldTag}(\\s[^>]*)?>`, 'gi');
    const regexClose = new RegExp(`</${oldTag}>`, 'gi');
    html = html.replace(regexOpen, `<${newTag}$1>`).replace(regexClose, ``);
  });
  container.innerHTML = html;
  // ⚠️ 所有子元素事件監聽器、輸入焦點、選區、表單狀態全失
}

方案三:虛擬 DOM Diff(大量結構變更、效能優先)

import morphdom from 'morphdom';

function swapTagsMorphdom(container, tagMap) {
  // 1. 產生目標 HTML
  const targetHTML = container.innerHTML
    .replace(/<(\/?)(\w+)([^>]*)>/g, (m, slash, tag, attrs) => 
      tagMap[tag.toLowerCase()] ? `<${slash}${tagMap[tag.toLowerCase()]}${attrs}>` : m
    );
  
  // 2. 建立暫存容器
  const temp = document.createElement('div');
  temp.innerHTML = targetHTML;
  
  // 3. Morphdom 智慧合併(保留未變更節點的狀態)
  morphdom(container, temp, {
    onBeforeElUpdated: (fromEl, toEl) => {
      // 可選:同步特定屬性、保留特定類別
      return true;
    },
    onNodeAdded: (node) => {
      // 新增節點初始化(如綁定事件委派)
    }
  });
}

安全流程:淨化 → 轉換 → 渲染

async function safeSwapAndRender(userHTML, container, tagMap) {
  // 1. 淨化使用者輸入
  const cleanHTML = DOMPurify.sanitize(userHTML, {
    ALLOWED_TAGS: ['p', 'br', 'b', 'i', 'strong', 'em', 'a', 'ul', 'ol', 'li', 'h1', 'h2', 'h3'],
    ALLOWED_ATTR: ['href', 'target', 'rel', 'class']
  });
  
  // 2. 轉換標籤(在 DocumentFragment 操作,不觸發重排)
  const doc = new DOMParser().parseFromString(cleanHTML, 'text/html');
  Object.entries(tagMap).forEach(([oldTag, newTag]) => {
    doc.querySelectorAll(oldTag).forEach(el => {
      const newEl = document.createElement(newTag);
      [...el.attributes].forEach(a => newEl.setAttribute(a.name, a.value));
      el.replaceWith(newEl);
    });
  });
  
  // 3. 替換容器內容
  container.innerHTML = doc.body.innerHTML;
  
  // 4. 事件委派(而非內聯 on*)
  container.addEventListener('click', e => {
    const link = e.target.closest('a[href]');
    if (link) { /* 處理導航 */ }
  });
}

React/Vue/Svelte 框架環境下的處理

  • React:用組件抽象,<RichText content={html} tagMap={map} /> 內部用 dompurify + html-react-parser
  • Vue:v-html="sanitizedHtml" + dompurify,或建立動態元件 <component :is="tag">
  • Svelte:{@html sanitizedHtml} + 客製化預處理器
  • 原生 Web Components:Shadow DOM 內操作,隔離樣式與全域選取器

效能基準參考(1000 節點)

方法耗時 (ms)記憶體保留狀態
DOM 遍歷 replaceChild~15-30低✅ 完整
innerHTML 重設~5-10中❌ 全失
morphdom~20-40中✅ 大部分
DocumentFragment 批次~8-15低✅ 新節點

標籤切換首選 **DOM 遍歷 replaceChild**(安全保狀態),大規模結構變更用 **morphdom**,**永遠先淨化使用者輸入**,框架專案請遵循框架資料流而非直接操作 DOM。

copyright © 萬盛學電腦網 all rights reserved