我有一些 JavaScript 函数,其中包含如下代码:
if (document.all)
{ document.getElementById('subrow').style.display = 'block'; }
else
{ document.getElementById('subrow').style.display = 'table-row'; }
IE 11 为 document.all
返回 false
所以上面的代码不再有效,但我需要它适用于早期版本的 IE 以及 IE 11 和其他浏览器。
我怎样才能做到这一点?早期版本的 IE 不理解 table-row
所以我必须能够区分。
最佳答案
不要——使用特征检测。
正如您所发现的,尝试使用间接测试(例如检查 document.all
)来检测浏览器是非常不可靠的。最佳做法是 use feature detection, not browser detection .
相反,如果您想知道是否支持 table-row
,您可以直接检查。这使您的代码更具可移植性,因为它不会将其绑定(bind)到特定版本。这是您可以根据 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;
}
}
关于javascript - 使用什么代替 document.all,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20992387/