萬盛學電腦網

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

IE6-8 動態創建 HTML5 新元素:document.createElement 與 innerHTML 坑點

IE6-8 不識別 HTML5 新元素(section、article、header 等),無法為其應用樣式、無法正常構建 DOM。經典解法是 document.createElement('tagName')「註冊」元素,但動態插入時有坑。

經典註冊腳本

<!--[if lt IE 9]>
<script>
  (function(tags){
    tags.forEach(function(t){ document.createElement(t); });
  })('article aside audio canvas details figcaption figure footer header hgroup main mark meter nav output progress section summary time video'.split(' '));
</script>
<![endif]-->

或引入 html5shiv(含 print 保護、媒體元素支援)。

動態插入坑點

var div = document.createElement('div');
div.innerHTML = '<section>section</section>';
alert(div.innerHTML); // IE6-8 顯示 "</section>",section 被剝離成無標籤文本節點

修正:包裹層 Hack

var div = document.createElement('div');
div.innerHTML = 'fixie<div>' + '<section>section</section>' + '</div>';
alert(div.innerHTML); // 正確保留 section
alert(div.lastChild.innerHTML); // 可正常訪問 section 內容

原理:在未知元素外層包一個已知元素(如 div),欺騙 IE 解析器正常構建子樹。

現代建議

  • 新專案放棄 IE6-8 支援,直接使用原生語義標籤。
  • 必須支援時,引入 html5shiv + innerShiv(或 html5shiv-printshiv)完整解決動態插入問題。
  • 服務端渲染(SSR)輸出完整 HTML,避免客戶端動態創建語義標籤。
copyright © 萬盛學電腦網 all rights reserved