【问题标题】:what to use instead of document.all用什么代替 document.all
【发布时间】:2014-01-08 20:30:43
【问题描述】:

我有一些 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所以要能区分。

【问题讨论】:

标签: javascript internet-explorer cross-browser


【解决方案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

【讨论】:

    【解决方案2】:

    您可以使用并检查"ActiveXObject" in window,这将适用于所有 IE 版本。

    document.all 是(!)快速检查它是否是 IE。

    所以:

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

    【讨论】:

    • 这似乎已经打破了 Firefox。 IE7 和 IE11 工作 - 该行变得可见。但是 Firefox 不再工作了。
    • 我很抱歉。我的表格行有错字(在我的网站上)。
    • 与使用 if (/msie/i.test(navigator.userAgent)) 相比,您的解决方案有什么好处/坏处吗?
    • @MartinSmellworse 更快(!)
    【解决方案3】:

    如果您想检查 IE,而不是 document.all,请这样做:

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

    注意:Trident是IE的渲染引擎,IE的所有版本都可以使用。

    【讨论】:

    • 适用于 IE7。它不适用于 IE11 或 Firefox。
    • 我很抱歉。我在表格行中有错字。
    • 与使用 if ("ActiveXObject" in window) 相比,您的解决方案有什么好处/坏处吗?
    • 尝试搜索IE的渲染引擎Trident
    • 我想知道 IE11 是否会将“块”应用到表格行 - 或者它是否已转为使用“表格行”。
    猜你喜欢
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    • 2013-11-04
    • 2018-06-18
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多