出錯的程式碼大致如下:
<p style="margin-top:0;">
<asp:TextBox ID="txtContent" runat="server" TextMode="MultiLine" Height="450" Width="98%"></asp:TextBox>
</p>
問題的根源是 IE7、IE8 中的 <p> 元素不支援 innerHTML。CodeMirror 作者也回報過這個問題,相關連結:
https://github.com/marijnh/CodeMirror2/issues/215
https://github.com/marijnh/CodeMirror2/commit/4886415d6054571f92fa4d5601ebe7d601e952ab
作者在原始碼中加了防禦性處理,偵測到這種情況時會丟出更清楚的錯誤訊息:
try { stringWidth("x"); }
catch (e) {
if (e.message.match(/runtime/i) || e.message.match(/運行時/i) )
e = new Error("A CodeMirror inside a P-style element does not work in Internet Explorer. (innerHTML bug)");
throw e;
}
解法很簡單:把 textarea 外層的 <p> 改成 <div> 即可。
<div style="margin-top:0;">
<asp:TextBox ID="txtContent" runat="server" TextMode="MultiLine" Height="450" Width="98%"></asp:TextBox>
</div>
IE 一直到 IE8 都沒有把 <p> 列入 innerHTML 可寫入的元素白名單(同樣受限的還有 table、select、head 等少數元素)。CodeMirror 需要量測字元寬度,做法是動態插入測試節點再讀取版面資訊,一碰到 <p> 就爆掉。
這也是一個實用經驗:用來當容器承載動態內容的元素,請選 <div>。<p> 在 HTML 規範中只能包含行內內容(phrasing content),把 textarea、div 這類區塊級元素塞進去本來就不合語意,瀏覽器在解析時也可能自動提早關閉這個段落標籤,造成 DOM 結構不如預期。
當然,以今天的標準來看,IE7/IE8 早已不在支援清單內,這個問題屬於歷史遺留。但「容器用 div、p 只放文字」這條原則,至今仍然適用。