Jquery uses navigator.userAgent.indexOf to determine the browser type and performs some processing. It is recommended that friends who are learning Jquery study it to understand the ideas.
Mainly used method: $.browser.['browser keyword']
$(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 source code of jQuery:
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 rules to match userAgent to determine the type and version of the browser.
version---browser version
msie- ---ie browser (Microsoft Internet Explorer)
mozilla-Firefox browser
opera--opera browser
How should we judge whether the current browser is IE6?
if($.browser.msie&&($ .browser.version == "6.0")&&!$.support.style){
alert("ie6");
}
Similarly, Jquery determines whether the browser is IE7
if($.browser.msie&&($.browser. version == "7.0")){
alert("ie7");
}
If you don’t want to use Jquery, you can use the Js code for your own use by slightly modifying the code:
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 )
}
When called with jquery The same, just remove the $ sign
If it is to determine the version of IE, I still recommend using IE’s conditional expression to write JS