写了一个判断当前浏览器类型及版本的方法,只在ie 8/11 、谷歌 、360 浏览器(不完全)上测试过,需要用到jquery
核心代码:
;(function($, window, document,undefined){ if(!window.browser){ var useragent = navigator.useragent.tolowercase(),uamatch; window.browser = {} /** * 判断是否为ie */ function isie(){ return (activexobject in window); } /** * 判断是否为谷歌浏览器 */ if(!uamatch){ uamatch = useragent.match(/chrome\/([\d.]+)/); if(uamatch!=null){ window.browser['name'] = 'chrome'; window.browser['version'] = uamatch[1]; } } /** * 判断是否为火狐浏览器 */ if(!uamatch){ uamatch = useragent.match(/firefox\/([\d.]+)/); if(uamatch!=null){ window.browser['name'] = 'firefox'; window.browser['version'] = uamatch[1]; } } /** * 判断是否为opera浏览器 */ if(!uamatch){ uamatch = useragent.match(/opera.([\d.]+)/); if(uamatch!=null){ window.browser['name'] = 'opera'; window.browser['version'] = uamatch[1]; } } /** * 判断是否为safari浏览器 */ if(!uamatch){ uamatch = useragent.match(/safari\/([\d.]+)/); if(uamatch!=null){ window.browser['name'] = 'safari'; window.browser['version'] = uamatch[1]; } } /** * 最后判断是否为ie */ if(!uamatch){ if(useragent.match(/msie ([\d.]+)/)!=null){ uamatch = useragent.match(/msie ([\d.]+)/); window.browser['name'] = 'ie'; window.browser['version'] = uamatch[1]; }else{ /** * ie10 */ if(isie() && !!document.attachevent && (function(){use strict;return !this;}())){ window.browser['name'] = 'ie'; window.browser['version'] = '10'; } /** * ie11 */ if(isie() && !document.attachevent){ window.browser['name'] = 'ie'; window.browser['version'] = '11'; } } } /** * 注册判断方法 */ if(!$.isie){ $.extend({ isie:function(){ return (window.browser.name == 'ie'); } }); } if(!$.ischrome){ $.extend({ ischrome:function(){ return (window.browser.name == 'chrome'); } }); } if(!$.isfirefox){ $.extend({ isfirefox:function(){ return (window.browser.name == 'firefox'); } }); } if(!$.isopera){ $.extend({ isopera:function(){ return (window.browser.name == 'opera'); } }); } if(!$.issafari){ $.extend({ issafari:function(){ return (window.browser.name == 'safari'); } }); } }})(jquery, window, document);
使用方法:
//使用方式console.log(window.browser);console.log($.isie());console.log($.ischrome());
脚本之家小编特提供的完整测试代码:
jquery 浏览器判断