js判断需要访问的页面在手机端还是PC端打开

14 篇文章 0 订阅
8 篇文章 0 订阅

方法一:

最原始写的是这样子, 发现在手机端打开pc端网页时,是跳转到pc端的链接,但是这个时候移动端页面显示不出来,而且会延迟页面渲染时间

<script type="text/javascript">
    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) {//如果是上述设备就会以手机域名打开
        // alert('手机端');
        window.location.href = 'http://www.xxx.com/mobile/';
    }else{//否则就是电脑域名打开
        // alert('电脑端');
        window.location.href = 'http://www.xxx.com';
    }
</script>
 

后来发现,其它不变,只要把判断改一下就ok啦。

PC端只判断跳转移动端

 //pc端项目

    if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM ){//如果是上述设备就会以手机域名打开 
        // alert('手机端');
        window.location.href = 'http://www.yyy.com/';//这里写移动端链接
    } 

 

移动端只判断跳转pc端

 //移动端项目

    if (!(bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM)){//如果是上述设备就会以手机域名打开,否则就是电脑域名打开
     // alert('pc端');
        window.location.href = 'http://www.xxx.com/';//这里为PC端链接
    }
 
 

方法二:

  <script type="text/javascript">

   //移动端项目

       if(!/Android|webOS|iPhone|iPad|BlackBerry/i.test(navigator.userAgent)) {

           window.location.href = "http:www.xxx";//这里为pc端项目

           }

   </script>
 <script type="text/javascript">
 
       //PC端项目

     //判断页面是在移动端还是PC端打开
    
    if(/Android|webOS|iPhone|iPad|BlackBerry/i.test(navigator.userAgent)) {
        window.location.href = "http:www.xxx.mobile";//这里为移动端链接
  }

  </script>

好啦,不管是使用方法一还是方法二,发现分开判断是比较好的选择,关于所判断的内容可根据需要自行修改~

相关参考链接:https://www.cnblogs.com/gaohuijiao/p/6736155.html

                         https://blog.csdn.net/cuilei210/article/details/78790848

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值