Home >Web Front-end >JS Tutorial >jquery code to determine browser type_jquery

jquery code to determine browser type_jquery

WBOY
WBOYOriginal
2016-05-16 17:48:411108browse

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']

Copy code Code 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 source code of jQuery:
Copy the 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 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?

Copy code The code is as follows:

if($.browser.msie&&($ .browser.version == "6.0")&&!$.support.style){
alert("ie6");
}

Similarly, Jquery determines whether the browser is IE7
Copy code The code is as follows:

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:
Copy 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 )
}

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
Copy code The code is as follows: