假设...
- ...这是笨拙的渲染引擎您要检测的旧版本IE,以使样式在旧IE中看起来正确(否则,请使用功能检测)
- ...您不能只向HTML添加条件注释 -例如,适用于可应用于任何页面的JS插件(否则,只需在<body>或上执行条件类的技巧即可<html>)
...那么这可能是最好的技巧(基于此非jQuery,灵活性稍差一些)。然后创建测试,然后删除适当的条件注释。
(在IE10 +“标准模式”中忽略了有条件的注释-但这应该没问题,因为IE10 +“标准模式”没有疯狂的渲染引擎!)
放入此功能:
function isIE( version, comparison ){
    var $div = $('<div style="display:none;"/>');
    // Don't chain these, in IE8 chaining stops some versions of jQuery writing the conditional comment properly
    $div.appendTo($('body'));
    $div.html('<!--[if '+(comparison||'')+' IE '+(version||'')+']><a> </a><![endif]-->');
    var ieTest = $div.find('a').length;
    $div.remove();
    return ieTest;
}
然后像这样使用它:
if(isIE()){ /* runs in all versions of IE after 4 before standards-mode 10 */ }
if(isIE(8)){ /* runs in IE8 */ }
if(isIE(9)){ /* runs in IE9 */ }
if(isIE(8,'lte')){ /* runs in IE8 or below */ }
if(isIE(6,'lte')){ /* if you need this, I pity you... */ }
我也建议缓存此函数的结果,这样就不必重复它。例如,您可以使用字符串(comparison||'')+' IE '+(version||'')作为键来存储并检查某个对象中某个对象的测试结果。