In Jquery, navigator. userAgent. indexOf is used to determine the browser type and perform some processing. It is recommended that you learn about Jquery and learn about the idea.
Main usage: $. browser. ['browser keyword ']
Copy codeThe Code is as follows:
$ (Function (){
If ($. browser. msie ){
Alert ("this is msie ");
} Else if ($. browser. safari ){
Alert ("this is safari! ");
} Else if ($. browser. mozilla ){
Alert ("this is mozilla! ");
} Else if ($. browser. opera ){
Alert ("this is opera ");
} Else {
Alert ("I don't konw! ");
}
Let's take a look at the jQuery source code:
Copy codeThe Code is as follows:
Var userAgent = navigator. userAgent. toLowerCase ();
// Figure out what browser is being used
JQuery. browser = {
Version: (userAgent. match (/. + (? : Rv | it | ra | ie) [\/:] ([\ d.] +)/) | []) [1],
Safari:/webkit/. test (userAgent ),
Opera:/opera/. test (userAgent ),
Msie:/msie/. test (userAgent )&&! /Opera/. test (userAgent ),
Mozilla:/mozilla/. test (userAgent )&&! /(Compatible | webkit)/. test (userAgent)
};
Jquery uses regular expressions to match userAgent to determine the browser type and version.
Version --- browser version
Msie ---- IE browser (Microsoft Internet Explorer)
Mozilla-Firefox
Opera-operabrowser
How can we determine whether the current browser is IE6?
Copy codeThe Code is as follows:
If ($. browser. msie & ($. browser. version = "6.0 ")&&! $. Support. style ){
Alert ("ie6 ");
}
Similarly, Jquery checks whether the browser is IE7.
Copy codeThe Code is as follows:
If ($. browser. msie & ($. browser. version = "7.0 ")){
Alert ("ie7 ");
}
If you do not want to use Jquery, you can modify the code to use the Js Code:
Copy codeThe Code is as follows:
Var userAgent = navigator. userAgent. toLowerCase ();
Browser = {
Version: (userAgent. match (/. + (? : Rv | it | ra | ie) [\/:] ([\ d.] +)/) | [0, '0']) [1],
Safari:/webkit/. test (userAgent ),
Opera:/opera/. test (userAgent ),
Msie:/msie/. test (userAgent )&&! /Opera/. test (userAgent ),
Mozilla:/mozilla/. test (userAgent )&&! /(Compatible | webkit)/. test (userAgent)
}
The call is the same as that of jquery, except that the $ symbol is removed.
To determine the version of IE, we recommend that you use the conditional expression of IE to write JavaScript code.
Copy codeThe Code is as follows:
<! -- [If IE]>
<Script type = "text/javascript">
Alert ("ie ");
</Script>
<! [Endif] -->
<! -- [If IE 6]>
<Script type = "text/javascript">
Alert ("ie6 ");
</Script>
<! [Endif] -->
<! -- [If IE 7]>
<Script type = "text/javascript">
Alert ("ie7 ");
</Script>
<! [Endif] -->
This is more accurate than we manually use $. browser to determine the IE version, and we do not need to record the use of jquery's browser.