如何确定用户在JavaScript中运行的IE版本?

17 javascript browser internet-explorer

在一些现有代码中,通过检查对象Browser.Engine.trident是否已定义并返回true,进行测试以查看用户是否正在运行IE.

但是如何确定用户是在运行IE6(或更早版本)还是运行IE7(或更高版本)?

JavaScript函数内部需要进行测试,因此条件注释似乎不合适.

kmi*_*ilo 18

从msdn 更有效地检测Internet Explorer:

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

function checkVersion()
{
  var msg = "You're not using Internet Explorer.";
  var ver = getInternetExplorerVersion();

  if ( ver > -1 )
  {
    if ( ver >= 6.0 ) 
      msg = "You're using a recent copy of Internet Explorer."
    else
      msg = "You should upgrade your copy of Internet Explorer.";
  }
  alert( msg );
}
Run Code Online (Sandbox Code Playgroud)


Jam*_*hes 12

如果你真的想确定你使用IE和特定版本,那么显然你可以使用IE的条件标签只在IE中运行某些代码.它不是那么漂亮,但至少你可以确定它真的是IE而不是一些欺骗版本.

<script>
    var isIE = false;
    var version = -1;
</script>
<!--[if IE 6]>
    <script>
        isIE = true;
        version = 6
    </script>
<![endif]-->
<!--[if IE 7]>
    <script>
        isIE = true;
        version = 7
    </script>
<![endif]-->
Run Code Online (Sandbox Code Playgroud)

这是非常自我解释的.在IE6 isIEtrueversion6,在IE7中isIEtrueversion7否则isIE是假的,version-1

或者,你可以使用jQuery中的代码来推广自己的解决方案.

var userAgent = navigator.userAgent.toLowerCase();
var version = (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
var isIE = /msie/.test( userAgent ) && !/opera/.test( userAgent ),    
Run Code Online (Sandbox Code Playgroud)