乘风原创程序

  • js判断设备是pc端还是移动端,来加载相应的页面
  • 2020/8/8 13:27:42
  • 最近在做一个前端项目,做了一个pc端的和一个移动端的,就想着可以把这两个页面关联起来,在pc端打开的时候展示pc端的页面,移动端打开展示移动端的页面,进而提升用户体验哈哈

    然后自己在网上找了很多中方法,大都有一个问题,就是打开网页的时候加载很慢,要等个好几秒才能加载出页面,用户体验极差,找了很久终于找到一个比较好的方法,页面加载也很快。
    话不多说,上代码!

    pc的端html页面头部加入下面的代码

    <script>
            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) {
                location.href = '移动端的页面地址';
            } else {
            }
    </script> 

    意思就是
    首先获取浏览器信息,调用match方法进行匹配属于哪一类浏览器,判断是否为移动端浏览器,如果是就跳转到移动端页面,pc端进入就不需要其他操作。

    移动端html页面头部加入以下代码

    <script>
            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) {
            } else {
                location.href = 'pc端的页面地址';
            }
    </script> 

    跟上面的原理是一样的,就不再赘述啦!

    本文地址:https://blog.csdn.net/qq_45745643/article/details/107869887