2014-01-08 38 views
2

我有一些JavaScript功能,包括類似的代碼:,而不是使用的document.all

if (document.all) 
{ document.getElementById('subrow').style.display = 'block'; } 
else 
{ document.getElementById('subrow').style.display = 'table-row'; } 

IE 11的回報falsedocument.all所以上面的代碼不再工作,但我需要它爲早期的工作IE版本以及IE 11和其他瀏覽器。

我該如何做到這一點? IE的早期版本不明白table-row,所以我必須能夠區分。

+0

- 興趣IE7及更高版本。和IE7不理解 '錶行' –

+0

參考: http://stackoverflow.com/questions/2408424/document-all-vs-document-getelementbyid http://stackoverflow.com/問題/ 13663023/what-does-document-all-mean – Muthu

+1

IE8 +確實明白'display:table-row' ... –

回答

1

不使用特徵檢測。

嘗試檢測間接測試瀏覽器,如檢查document.all,正如您發現的那樣,非常不可靠。最佳做法是use feature detection, not browser detection

相反,如果您想知道是否支持table-row,則可以直接進行檢查。這使得您的代碼更具可移植性,因爲它不會將其綁定到特定版本。這裏是你可以基於該Modernizr display test for table layout做到這一點的一種方法:我不是

function isTableRowSupported() { 
    try { 
     var style = document.createElement("div").style; 
     style.display = 'table-row'; 
     return style.display == 'table-row'; 
    } catch (e) { 
     return false; 
    } 
} 

jsFiddle demo

0

您可以使用並檢查"ActiveXObject" in window而不是將適用於所有IE版本。

document.all was(!)一個快速檢查,看看它是否是IE瀏覽器。

這樣:

if ("ActiveXObject" in window) 
{ document.getElementById('subrow').style.display = 'block'; } 
else 
{ document.getElementById('subrow').style.display = 'table-row'; } 
+0

這似乎已經打破了它的Firefox。 IE7和IE11的工作 - 該行變得可見。但Firefox不再有效。 –

+0

我的歉意。我在表格行(在我​​的網站上)中有一個錯字。 –

+0

與使用if(/msie/i.test(navigator.userAgent))相比,解決方案有什麼優點/缺點嗎? –

0

相反的document.all的,如果你想要做的IE瀏覽器的檢查,然後做這樣的:

if(/msie|trident/i.test(navigator.userAgent)){ 
    document.getElementById('subrow').style.display = 'block'; 
} else { 
    document.getElementById('subrow').style.display = 'table-row'; 
} 

注:三叉戟是IE的渲染引擎,它在IE的所有版本中都可用。

+0

這適用於IE7。它不適用於IE11或Firefox。 –

+0

我的歉意。我在表格行中有一個錯字。 –

+0

與使用if(窗口中的「ActiveXObject」)相比,解決方案有什麼優點/缺點嗎? –