tohokuaikiのチラシの裏

技術的ネタとか。

jQueryでIEのバージョンを判別する方法

jQuery1.6でうまく動作しないようです。

ということで、http://w3g.jp/blog/tools/js_browser_sniffing を参考に書き換え

var isIE = function()
{
    var version = arguments.length ? arguments[0] : '';

    var _ua = (function() {
        return {
          ltIE6:typeof window.addEventListener == "undefined" && typeof document.documentElement.style.maxHeight == "undefined",
          ltIE7:typeof window.addEventListener == "undefined" && typeof document.querySelectorAll == "undefined",
          ltIE8:typeof window.addEventListener == "undefined" && typeof document.getElementsByClassName == "undefined",
          ie:document.uniqueID,
          firefox:window.globalStorage,
          opera:window.opera,
          webkit:!document.uniqueID && !window.opera && !window.globalStorage && window.localStorage,
          mobile:/android|iphone|ipad|ipod/i.test(navigator.userAgent.toLowerCase())
        }
    })();

    switch (version) {
      case 6:
        return _ua.ltIE6;
        break;
      case 7:
        return _ua.ltIE7;
        break;
      case 8:
        return _ua.ltIE8;
        break;
      case 9:
        return _ua.ltIE9;
        break;
      default:
        return _ua.ie;
    }
}


http://w3g.jp/blog/tools/jquery_browser_sniffing
を参考に簡単関数化

function isIE()
{
    version = arguments.length >= 1 ? parseInt(arguments[0]) : '';
    switch (version){
      case 6:
        return !jQuery.support.opacity && 
          !jQuery.support.style && 
            typeof document.documentElement.style.maxHeight == "undefined" ;
        break;
      case 7:
        return !jQuery.support.opacity &&
          !jQuery.support.style &&
            typeof document.documentElement.style.maxHeight != "undefined" ;
        break;
      case 8:
        return !jQuery.support.opacity && jQuery.support.style;
        break;
      case 9:
        return !jQuery.support.noCloneEvent && jQuery.support.opacity;
      default :
        return !jQuery.support.opacity;
    }
    
    return false;
}

alert("isIE6 => " + isIE(6) + 
      "\n isIE7 => " + isIE(7) + 
      "\n isIE8 => " + isIE(8) +
      "\n isIE9 => " + isIE(9) +
      "\n isIE => " + isIE());