如何在客户端判断浏览器的类型(Detecting IE7+ in JavaScript)

 
Today I was updating some Javascript code to support the rapidly-approaching Internet Explorer 7. There were a few places in the code where there were IE-specific workarounds, which happily are no longer needed in IE 7
thanks to its improved standards support. Yay position:fixed!

Where the code used to check for if (ie) { ... }, now I wanted it to check for if (ie6OrLower) { ... }. So how to you tell the difference between IE 6 and IE 7+? You could parse the user-agent string, but I’d rather detect changes in the javascript object model. Here’s what I came up with:

if (typeof document.body.style.maxHeight != "undefined") {
  // IE 7, mozilla, safari, opera 9
} else {
  // IE6, older browsers
}
This distinguishes between browsers based on the fact that IE 7 knows about the maxHeight css property, whereas previous versions of IE didn’t. Does that seem like a sane approach to you?

Update: over at Ajaxian Arjan points out that it’s a bit simpler to check for window.XmlHttpRequest, which is also new in IE 7.




JAVASCRIPT:

  1.  
  2. if ( typeof document. body. style. maxHeight != "undefined" ) {
  3.   // IE 7, mozilla, safari, opera 9
  4. } else {
  5.   // IE6, older browsers
  6. }



    You can also use the XHR check:

  7. if (window.XMLHttpRequest) {
    // IE 7, mozilla, safari, opera 9
    } else {
    // IE6, older browsers
    }



    If script is executed width , then document.body is not available yet.

    if (window.XMLHttpRequest) {
    if(document.epando){
       alert("ie7");
    //IE7
    }else{
    //mozilla, safari, opera 9…etc
       alert("mozilla");
    }
    } else {
    // IE6, older browsers
       alert("ie6");
    }



    偶测试了一下,发现这最后一种方法区别不了 IE7还是firefox,请高人指点一下!

你可能感兴趣的:(JavaScript)