方法一:
最原始写的是这样子, 发现在手机端打开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