How do I detect IE 8 with jQuery?

前端 未结 12 1414
一生所求
一生所求 2020-11-30 19:14

I need to detect not only the browser type but version as well using jQuery. Mostly I need to find out if it is IE 8 or not.

I am not sure if I am doing it correctly

12条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 19:43

    Assuming...

    • ...that it's the crunky rendering engine of old versions of IE you're interested in detecting, to make a style look right in old IE (otherwise, use feature detection)
    • ...that you can't just add conditional comments to the HTML - e.g. for JS plugins that can be applied to any page (otherwise, just do the trick of conditional classes on or )

    ...then this is probably the best trick (based on this non-jQuery, slightly less flexible variant). It creates then tests for then removes an appropriate conditional comment.

    (Conditional comments are ignored in IE10+ 'standards mode' - but that should be fine since IE10+ 'standards mode' doesn't have a crazy rendering engine!)

    Drop in this function:

    function isIE( version, comparison ){
        var $div = $('
    '); // Don't chain these, in IE8 chaining stops some versions of jQuery writing the conditional comment properly $div.appendTo($('body')); $div.html(''); var ieTest = $div.find('a').length; $div.remove(); return ieTest; }

    Then use it like this:

    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... */ }
    

    I'd also suggest caching the results of this function so you don't have to repeat it. For example, you could use the string (comparison||'')+' IE '+(version||'') as a key to store and check for the result of this test in an object somewhere.

提交回复
热议问题