閱讀783 返回首頁    go 阿裏雲 go 技術社區[雲棲]


jQuery中通過$.browser來判斷瀏覽器

一、使用方法 

語法:$.browser.["瀏覽器關鍵字"] 

$(function() { 
if($.browser.msie) { 
alert("this is IE"); 

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!"); 


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使用的是通過正則來匹配userAgent判斷瀏覽器的種類和版本. 


二、判斷瀏覽器版本
若判斷當前瀏覽器是否是IE6 
$.browser.msie && ($.browser.version == "6.0")&&!$.support.style 
同樣jQuery判斷瀏覽器是否為IE7 

$.browser.msie&&($.browser.version == "7.0") 
如果不考慮向後兼容性,又不想為了判斷各瀏覽器類型而導入jQuery 

判斷IE最簡單的方法是 
if(document.all){ 
alert("IE6");

$.browser是通過正則表達式來匹配userAgent來判斷瀏覽器版本和種類的.jquery1.3.2版本的文檔中已經聲明jquery.browser及jquery.browser.version建議棄用,可以使用jquery.support來代替 但是目前的情況來看,jquery.support並不好用,而且是非常的難用,還是老老實實用$.browser來判斷瀏覽器類型吧。


三、IE的條件表達式也可以書寫JS 

<!--[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]-->
比通過$.browser來判斷IE版本更精準,也不用去記jquery的browser的使用方法了。


原帖地址:https://www.poluoluo.com/jzxy/201110/145284.html

最後更新:2017-04-03 16:59:46

  上一篇:go 像黑客一樣思考問題
  下一篇:go hadoop拷貝文件時 org.apache.hadoop.ipc.RemoteException異常的解決