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

方法一(判断终端设备):

php文件:
1 $addr = "http://".$_SERVER['SERVER_NAME']."/Home/Index/index_m.html";
2 $this->assign('addr',$addr);

js文件:

 1 <script type="text/javascript">
 2   $(document).ready(function(){
 3   var mobileAgent = new Array("iphone", "ipod", "ipad", "android", "mobile", "blackberry", "webos", "incognito", "webmate", "bada", "nokia", "lg", "ucweb", "skyfire");
 4   var browser = navigator.userAgent.toLowerCase();
 5   var isMobile = false;
 6   var addr = $("#addr").val();
 7   for (var i=0; i<mobileAgent.length; i++){ if (browser.indexOf(mobileAgent[i])!=-1){ isMobile = true;
 8   //alert(mobileAgent[i]);
 9      location.href = addr;
10       break; } }
11      });
12   </script>

html文件:

1 <input type="hidden" name="addr" id="addr" value="{$addr}">

 

 

 

 

 

方法二(判断终端设备):

js文件:

1 if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
2      window.location.href = "https://www.baidu.com/";
3  } else {
4      window.location.href = "http://news.baidu.com/";
5  }
实际上就是利用正则去判断 navigator.useragent 是否含有 Android/webOs/iphone 等字符串,并且利用修饰符 "i" 做了不区分大小写,然后用正则的方法 test 去判断是否满足。

 

 

 

 

 

 

方法三(根据屏幕分辨率跳转手机端页面):

如果一个页面需要PC和手机端,那么可能要做两个页面分别对应PC和手机端。假设PC端的页面为index.html,手机端的页面为mobile.html,且两文件都在相同目录路径中,那么关于前端页面排版布局适应性的相关代码如下:

index.html

 1     <!-- 页面跳转 -->
 2     <script type="text/javascript">
 3         var oWidth = document.documentElement.clientWidth || document.body.clientWidth;
 4         if (oWidth > 1200) {} else {
 5             window.location.href = "mobile.html";
 6         }
 7 
 8         //当对浏览器窗口调整大小时
 9         window.addEventListener("resize", function () {
10             var oWidth = document.documentElement.clientWidth || document.body.clientWidth;
11             if (oWidth > 1200) {} else {
12                 window.location.href = "mobile.html";
13             }
14         }, false);
15     </script>

 

 

mobile.html

 1 <!-- 页面跳转 -->
 2 <script type="text/javascript">
 3         var oWidth = document.documentElement.clientWidth || document.body.clientWidth;
 4         if (oWidth < 1200) {} else {
 5             window.location.href = "index.html";
 6         }
 7 
 8         //在用户旋转移动设备时
 9         window.addEventListener("orientationchange", function () {
10             var oWidth = document.documentElement.clientWidth || document.body.clientWidth;
11 
12             if (oWidth < 1200) {
13 
14             } else {
15                 window.location.href = "index.html";
16             }
17         }, false);
18 
19         //当对浏览器窗口调整大小时
20         window.addEventListener("resize", function () {
21             var oWidth = document.documentElement.clientWidth || document.body.clientWidth;
22             if (oWidth < 1200) {} else {
23                 window.location.href = "index.html";
24             }
25         }, false);
26 </script>

 

这样即可实现根据屏幕大小来动态改变显示哪个html文件页面。

 

posted @ 2018-04-10 18:49  哟风  Views(280)  Comments(0)    收藏  举报