close
文章出處
web開發就不得不面對瀏覽器兼容性問題,特別是IE的兼容問題。在前端代碼中經常要處理一些兼容格式,為了解決這個問題網上找了找識別瀏覽器版本的方法。
常規js方法
找到一個方法,還不錯,可以識別出各種瀏覽器的版本:
1 /** 2 * 獲取瀏覽器版本 3 * @returns {Array} 4 */ 5 function browserVersion() { 6 var browserType = ""; 7 var browserVersion = 0; 8 var ua = navigator.userAgent.toLocaleLowerCase(); 9 10 if (ua.match(/msie/) != null) { 11 browserType = "IE"; 12 browserVersion = ua.match(/msie ([\d.]+)/)[1]; 13 } else if (ua.match(/trident/) != null && ua.match(/rv/) != null) { 14 browserType = "Edge"; 15 browserVersion = ua.match(/rv:([\d.]+)/)[1]; 16 } else if (ua.match(/firefox/) != null) { 17 browserType = "Firefox"; 18 browserVersion = (ua.match(/firefox\/([\d.]+)/)[1]).replace(/[^0-9.]/ig,""); 19 } else if (ua.match(/opera/) != null) { 20 browserType = "Opera"; 21 browserVersion = (ua.match(/opera\/([\d.]+)/)[1]).replace(/[^0-9.]/ig,""); 22 } else if (ua.match(/chrome/) != null) { 23 browserType = "Chrome"; 24 browserVersion = (ua.match(/chrome\/([\d.]+)/)[1]).replace(/[^0-9.]/ig,""); 25 } else if (ua.match(/safari/) != null) { 26 browserType = "Safari"; 27 browserVersion = (ua.match(/safari\/([\d.]+)/)[1]).replace(/[^0-9.]/ig,""); 28 } 29 var arr = new Array(browserType, browserVersion); 30 return arr; 31 }
在代碼中直接使用也比較簡單了。
IE的條件注釋
在一次偶然的機會看網金社的前端代碼,發現一段很特別的注釋:


這個貌似有點神奇,看代碼的意思是一個跳轉,但顯示是注釋的語句,于是抱著試一試的態度將瀏覽器切換到IE低版本,果然是有效果的。趕緊網上開始找這方面的資料,有一些用法說明,看來確實是可行的方案。
條件注釋屬性:
gt : greater than,選擇條件版本以上版本,不包含條件版本
lt : less than,選擇條件版本以下版本,不包含條件版本
gte : greater than or equal,選擇條件版本以上版本,包含條件版本
lte : less than or equal,選擇條件版本以下版本,包含條件版本
! : 選擇條件版本以外所有版本,無論高低
用法:<!--[if IE]>用于 IE <![endif]-->
<!--[if IE 6]>用于 IE6 <![endif]-->
<!--[if IE 7]>用于 IE7 <![endif]-->
<!--[if IE 8]>用于 IE8 <![endif]-->
<!--[if IE 9]>用于 IE9 <![endif]-->
<!--[if gt IE 6]> 用于 IE6 以上版本<![endif]-->
<!--[if lte IE 7]> 用于 IE7或更低版本 <![endif]-->
<!--[if gte IE 8]>用于 IE8 或更高版本 <![endif]-->
<!--[if lt IE 9]>用于 IE9 以下版本<![endif]-->
<!--[if !IE]> -->用于非 IE <!-- <![endif]-->
![]() |
不含病毒。www.avast.com |
全站熱搜