天天看點

document.createElement IE 相容

IE9 : DOM Exception: INVALID_CHARACTER_ERR (5)

以下代碼在IE8下運作通過,在IE9中出錯:

document.createElement('<iframe id="yui-history-iframe" src="../../images/defaults/transparent-pixel.gif" style="position:absolute;top:0;left:0;width:1px;height:1px;visibility:hidden;"></iframe>');

錯誤提示:exception : SCRIPT5022: DOM Exception: INVALID_CHARACTER_ERR (5)

思路分析:

第一步:相容IE9,firefox,Opera,Safari等浏覽器;

var iframe = document.createElement("iframe");

iframe.setAttribute("id", "yui-history-iframe");

iframe.setAttribute("src", "../../images/defaults/transparent-pixel.gif");

iframe.setAttribute("style","position:absolute;top:0;left:0;width:1px;height:1px;visibility:hidden;");

第二步:相容IE6-8:由于ie6-8 不能修改iframe的name屬性

var oFrame = isIE ? document.createElement("<iframe name=/"" + this._FrameName + "/">") : document.createElement("iframe");

oFrame.name = "iframName";

綜合解決辦法:

var isIE = (document.all) ? true : false;//這裡僅僅簡單的對是否是IE進行判斷,詳細浏覽器判斷:請參考浏覽器類型偵測

var ua = navigator.userAgent.toLowerCase().match(/msie ([/d.]+)/)[1];

if (ua == "9.0") {

isIE = false;

}

var oFrame = isIE ? document.createElement("<iframe name=/"" + this._FrameName + "/">") : document.createElement("iframe");

oFrame.name = "iframName";

繼續閱讀