Jquery is used to determine the browser type. If this method is used only to determine the browser type, it is not recommended to use it. It is only recommended when jquery is used, because there is no need to load such a large class library because of such a small function. Use navigator in Jquery. userAgent. indexOf is used to determine the browser type and perform some processing. It is recommended that you learn Jquery and learn about the ideas.
Main usage: $. browser. ['browser keyword ']
The 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:
The 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?
The Code is as follows:
If ($. browser. msie & ($. browser. version = "6.0 ")&&! $. Support. style ){
Alert ("ie6 ");
}
Similarly, Jquery checks whether the browser is IE7.
The 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:
The 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.
The Code is as follows:
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.