Pick CSS for IE8 可在模拟器中运行但不能直接在 IE8 上运行

Pick CSS for IE8 works in emulator but NOT directly on IE8

我正在使用 jQuery 检测浏览器版本并根据浏览器版本设置 CSS。

if ( getBrowserVersion() == '8' ) {
    $('head').append('<link href="/css/MSIE8.css" rel="stylesheet" id="MSIECSS8" />');
}

function getBrowserVersion() {
    var ua = navigator.userAgent, tem,
        M = ua.match(/(opera|chrome|safari|firefox|msie|wow64|trident(?=\/))\/?\s*(\d+)/i) || [];
    if ( /trident/i.test( M[1] ) ) {
        tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
        return 'IE ' + ( tem[1] || '' );
    }
}

这在我使用 F12 开发人员工具在 IE11 中模拟 IE8 时有效。但是当我直接在 IE8 上 运行 网站时,它不会选择 CSS。关于如何使这项工作有任何想法吗?感谢您的帮助!

除非绝对必要,否则您应该避免所有用户代理嗅探。在这种情况下,没有必要。如果您希望为 Internet Explorer 8 加载自定义样式表,请使用浏览器本身提供的功能,即 Conditional Comments:

<head>
    <!--[if IE 8]>
        <link href="/css/MSIE8.css" rel="stylesheet" id="MSIECSS8" />
    <![endif]-->
</head>

这将在 Internet Explorer 10 之前的版本 中被解析。并且只有在 Internet Explorer 8 中才会将 MSIE8.css 样式表添加到文档。

一般来说,除此之外的任何事情都会不必要地使您的项目复杂化。