js 判斷是什麼型別瀏覽器
複製代碼代碼如下:
if ( window.sidebar && "object" == typeof( window.sidebar ) && "function" == typeof( window.sidebar.addPanel ) ) // firefox
{
}
else if ( document.all && "object" == typeof( window.external ) ) // ie
{
}
js用來區別IE與其他瀏覽器及IE6-8之間的方法。
1、document.all
2、!!window.ActiveXObject;
使用方法如下:
if (document.all){
alert(”IE瀏覽器”);
}else{
alert(”非IE瀏覽器”);
}
if (!!window.ActiveXObject){
alert(”IE瀏覽器”);
}else{
alert(”非IE瀏覽器”);
}
下面是區別IE6、IE7、IE8之間的方法:
var isIE=!!window.ActiveXObject;
var isIE6=isIE&&!window.XMLHttpRequest;
var isIE8=isIE&&!!document.documentMode;
var isIE7=isIE&&!isIE6&&!isIE8;
if (isIE){
if (isIE6){
alert(”ie6″);
}else if (isIE8){
alert(”ie8″);
}else if (isIE7){
alert(”ie7″);
}
}
首先我們確保這個瀏覽器為IE的情況下,進行了在一次的檢測,如果你對此有懷疑,可以測試一下。
我這裡就直接使用在判斷中了,你也可以先將他們宣告成變數來使用。據說火狐以後也會加入document.all這個方法,所以建議使用第二種方法,應該會安全一些。
用navigator.userAgent.indexOf()來區分多瀏覽器,程式碼範例如下:
複製代碼代碼如下:
<coding-1 lang="other">
<script type="text/javascript">
var browser={
versions:function(){
var u = navigator.userAgent, app = navigator.appVersion;
return {
trident: u.indexOf('Trident') > -1, //IE內核
presto: u.indexOf('Presto') > -1, //opera內核
webKit: u.indexOf('AppleWebKit') > -1, //蘋果、Google內核
gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐內核
mobile: !!u.match(/AppleWebKit.*Mobile.*/)||!!u.match(/AppleWebKit/), //是否為行動終端
ios: !!u.match(//(i[^;]+;( U;)? CPU.+Mac OS X/), //ios終端機
android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android終端機或uc瀏覽器
iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否為iPhone或QQHD瀏覽器
iPad: u.indexOf('iPad') > -1, //是否iPad
webApp: u.indexOf('Safari') == -1 //是否web應該程序,沒有頭部與底部
};
}()
}
document.writeln(" 是否為行動終端: "+browser.versions.mobile);
document.writeln(" ios終端: "+browser.versions.ios);
document.writeln(" android終端: "+browser.versions.android);
document.writeln(" 是否為iPhone: "+browser.versions.iPhone);
document.writeln(" 是否iPad: "+browser.versions.iPad);
document.writeln(navigator.userAgent);
</script>
</coding>
JavaScript不管是判斷PC瀏覽器還是手機瀏覽器,都是透過User Agent 來判斷。