【问题标题】:Serve alternative CSS for IE11 and below using JavaScript?使用 JavaScript 为 IE11 及以下版本提供替代 CSS?
【发布时间】:2022-01-28 11:40:26
【问题描述】:

Stackoverflow 上有很多关于如何检测 IE11 的examples,但我不确定如何在 JavaScript 条件语句中使用它。

我正在使用 Tailwind CSS,但它不支持 IE11 及以下版本。我想要一种至少通过替代 CSS 文件提供某种布局的方法。

我如何用 JavaScript 做这样的事情?

if (IE11) {
    <link rel="stylesheet" href="/css/ie11.css">
  } else if (IE10) {
     <link rel="stylesheet" href="/css/ie10.css">
  } else if (IE9) {
    <link rel="stylesheet" href="/css/ie9.css">
  } else if (IE8) { {
    <link rel="stylesheet" href="/css/ie8.css">
  } else {
    <link rel="stylesheet" href="/css/tailwind.css">
  }
}

我很欣赏全球 IE11 的使用率非常低,但我希望能够利用 Tailwind CSS 并在需要时提供支持旧浏览器的选项。

【问题讨论】:

  • 为什么您对链接到的问题不满意?
  • 我看不出我会如何调整它,所以它按照我的例子工作。
  • 我猜第一件事是您将 HTML 代码与 JS 代码混合在一起。你不能这样做。因为它们不是一回事。你真的应该专注于一个 - 你是 JS 吗?然后add the stylesheets with JS。您想在普通 HTML 代码中添加 HTML 标签吗?那么你可能应该use HTML and CSS only
  • 谢谢,我认为这可能是一个更好的解决方案。 getbutterfly.com/…

标签: javascript internet-explorer-11


【解决方案1】:

可以使用window.document.documentMode判断当前浏览器是否为IE。然后将资源动态导入页面。

简单代码:

<script>
        var ieVersion = window.document.documentMode;
        if (ieVersion != 'undefined' & ieVersion > 7 && ieVersion < 12) {
            console.log('Load in IE ' + ieVersion);
            importJsResource(ieVersion);
        } else {
            console.log('Not in IE 8-11..');
            ieVersion = "tailwind";
            importJsResource(ieVersion);
        }

        function importJsResource(version) {
            var fileref = document.createElement("link");
            fileref.rel = "stylesheet";
            fileref.type = "text/css";
            if (ieVersion == 'tailwind') {
                fileref.href = "/Content/tailwind.css";
            } else {
                fileref.href = "/Content/ie" + version + ".css";
            }
            document.getElementsByTagName("head")[0].appendChild(fileref);
        }
    </script>

【讨论】:

  • 这太好了,非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-03
  • 2012-02-15
  • 1970-01-01
  • 2016-10-31
相关资源
最近更新 更多