JavaScript判断访问来源是手机还是电脑,用的哪种浏览器
本文介绍如何利用JavaScript通过User Agent字符串区分PC与移动设备,并识别具体浏览器内核。内容涵盖Firefox、IE及Opera的早期特征检测,重点解析IE6至IE8的版本判断逻辑,以及基于navigator.userAgent的多浏览器兼容性检测代码实现。
JavaScript判断访问来源是手机还是电脑,用的哪种浏览器
使用JavaScript识别当前访问所使用的浏览器类型。
具体实现代码示例如下:
if ( window.sidebar && "object" == typeof( window.sidebar ) && "function" == typeof( window.sidebar.addPanel ) ) // firefox
{
}
else if ( document.all && "object" == typeof( window.external ) ) // ie
{
}以下方法用于区分IE浏览器与其他浏览器,以及区分IE6至IE8之间的具体版本。
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,然后进行二次检测。如有疑虑,建议实际测试验证。
此处直接嵌入判断逻辑,也可先声明为变量复用。鉴于Firefox未来可能加入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, //苹果、谷歌内核
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>无论是判断PC浏览器还是手机浏览器,核心原理均是通过User Agent进行识别。
anime.js 快速入门:怎么引入库并编写第一个 DOM 动画
2026-11-05 14:22:43
在线JS解密后变量名仍乱码?结合浏览器DevTools调试还原
2026-11-04 20:26:01
怎么在浏览器中运行JavaScript代码并查看输出结果
2026-11-04 09:07:33
JS 获取屏幕分辨率:window.screen.width 与 height 用法
2026-11-04 08:52:48
为什么推荐用DOMContentLoaded代替window.onload初始化JS
2026-11-04 08:42:33
