js判断是否为手机端访问

时间:2022-12-30 03:17:16

随着移动端越来越重要,pc和移动端网站后台系统可能是同一个,登录或者某个特定时期需要根据不同访问来源,跳转不同页面或者做不同的处理;

这时我们就需要js的 navigator 对象;

我们先了解一下navigator 对象相关的属性:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS的navigator对象</title>
</head>
<body>
<div id="txt"></div>
<script>
var txt = "<p>浏览器代号: " + navigator.appCodeName + "</p>";
txt+= "<p>浏览器名称: " + navigator.appName + "</p>";
txt+= "<p>浏览器版本: " + navigator.appVersion + "</p>";
txt+= "<p>启用Cookies: " + navigator.cookieEnabled + "</p>";
txt+= "<p>硬件平台: " + navigator.platform + "</p>";
txt+= "<p>用户代理: " + navigator.userAgent + "</p>";
txt+= "<p>用户代理语言: " + navigator.systemLanguage + "</p>";
document.getElementById("txt").innerHTML=txt;
</script>
</body>
</html>

我们可以用其中的用户代理进行判断:userAgent

示例一:

<script type="text/javascript">

var ua = navigator.userAgent;

var ipad = ua.match(/(iPad).*OS\s([\d_]+)/),

isIphone =!ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/),

isAndroid = ua.match(/(Android)\s+([\d.]+)/),

isMobile = isIphone || isAndroid;

//判断

if(isMobile){

}else{

}

</script>

示例二:

function check() {
var userAgentInfo=navigator.userAgent;
var Agents =new Array("Android","iPhone","SymbianOS","Windows Phone","iPad","iPod");
var flag=true;
for(var v=0;v<Agents.length;v++) {
if(userAgentInfo.indexOf(Agents[v])>0) {
flag=false;
break;
}
}
return flag;
}

示例三:

function() {
var sUserAgent = navigator.userAgent;
if (sUserAgent.indexOf('Android') > -1 || sUserAgent.indexOf('iPhone') > -1 || sUserAgent.indexOf('iPad') > -1 || sUserAgent.indexOf('iPod') > -1 || sUserAgent.indexOf('Symbian') > -1) {
location.href = '要跳转的手机网址';
} else {}
}

示例四:

function IsPC() {
var userAgentInfo = navigator.userAgent;
var Agents = ["Android", "iPhone",
"SymbianOS", "Windows Phone",
"iPad", "iPod"];
var flag = true;
for (var v = 0; v < Agents.length; v++) {
if (userAgentInfo.indexOf(Agents[v]) > 0) {
flag = false;
break;
}
}
return flag;
} var flag = IsPC(); //true为PC端,false为手机端