详解JS判断页面是在手机端还是在PC端打开的方法

作者:微光

时间:2026-10-23

浏览:447

本文介绍如何利用JavaScript的Navigator对象及正则表达式,在统一入口index.html中自动识别设备类型。通过解析UserAgent字符串,实现PC端与移动端页面的自动跳转与适配,提供冗余代码与正则优化两种方案,确保不同设备访问时的最佳体验。

文章目录

项目目录与统一入口思路

我们的目标是实现PC端与移动端文件共用同一个入口,并能根据访问设备自动适配显示不同的内容。首先查看项目的目录结构:

项目目录与统一入口思路

在index.html文件中,通过JavaScript控制逻辑来选择加载对应设备文件夹下的文件。这里主要利用Navigator对象,该对象包含了浏览器的相关信息。index.html的实现非常简洁,具体代码如下:

基于Navigator对象的JS判断实现


<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
		<script type="text/javascript">
			function browserRedirect() {
	  var sUserAgent = navigator.userAgent.toLowerCase();
	  var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
	  var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
	  var bIsMidp = sUserAgent.match(/midp/i) == "midp";
	  var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
	  var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
	  var bIsAndroid = sUserAgent.match(/android/i) == "android";
	  var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
	  var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
	  if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
	  //跳转移动端页面
	  window.location.href="http://f.jcngame.com/fanfan20171208/mobile/index.html" rel="external nofollow" rel="external nofollow" ;
	  } else {
	  //跳转pc端页面
	  window.location.href="http://f.jcngame.com/fanfan20171208//fanmai/index.html" rel="external nofollow" rel="external nofollow" ;
	  }
	 }
			browserRedirect(); 
		</script>
	</head>
	<body>
		
	</body>
</html>

补充说明,考虑到之前的代码可能存在冗余,现在使用正则表达式进行了优化,代码如下:

使用正则表达式优化判断逻辑


<script type="text/javascript">
	function browserRedirect() {
  var sUserAgent = navigator.userAgent.toLowerCase();
  if (/ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile/.test(sUserAgent)) {
  //跳转移动端页面
  window.location.href="http://f.jcngame.com/fanfan20171208/mobile/index.html" rel="external nofollow" rel="external nofollow" ;
  } else {
  //跳转pc端页面
  window.location.href="http://f.jcngame.com/fanfan20171208//fanmai/index.html" rel="external nofollow" rel="external nofollow" ;
  }
 }
	browserRedirect(); 
</script>

项目目录与统一入口思路

项目目录与统一入口思路

以上介绍了利用JS判断页面是在手机端还是在PC端打开的方法详解整合,希望对大家有所帮助。如果大家有任何疑问请留言,小编会及时回复。在此也非常感谢大家对本站网站的支持!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章