欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

js判断PC端与移动端跳转

程序员文章站 2022-12-13 10:51:40
在网上看到很多这样类似的代码,但是有的很复杂,或者有的没有判断完全,上次经理去见完客户回来讲,使用苹果浏览打开pc端(pc已经做了识别跳转)会自动跳转到移动端的网页去,后来...

在网上看到很多这样类似的代码,但是有的很复杂,或者有的没有判断完全,上次经理去见完客户回来讲,使用苹果浏览打开pc端(pc已经做了识别跳转)会自动跳转到移动端的网页去,后来经测试才发现

document.writeln(" 是否为移动终端: "+browser.versions.mobile+"</br>");  //打印出来 true

所以在完整版的代码中 第一层if 判断一直是true

以上的原因是因为,网上流传的判断为: 

mobile: !! u.match(/applewebkit.*mobile.*/) || !! u.match(/applewebkit/), //是否为移动终端

判断不完整才会造成这种原因。

正确的判断应该为:

mobile: !! u.match(/applewebkit.*mobile.*/) || !! u.match(/applewebkit/) && u.indexof('qihu') && u.indexof('qihu') > -1 && u.indexof('chrome') < 0, //是否为移动终端

测试程序代码

var browser = {
 versions: function() {
  var u = navigator.useragent;
  return {
   trident: u.indexof('trident') > -1,
   presto: u.indexof('presto') > -1,
   webkit: u.indexof('applewebkit') > -1,
   gecko: u.indexof('gecko') > -1 && u.indexof('khtml') == -1,
   mobile: !! u.match(/applewebkit.*mobile.*/) || !! u.match(/applewebkit/) && u.indexof('qihu') && u.indexof('qihu') > -1 && u.indexof('chrome') < 0,
   ios: !!u.match(/\(i[^;]+;( u;)? cpu.+mac os x/),
   android: u.indexof('android') > -1 || u.indexof('linux') > -1,
   iphone: u.indexof('iphone') > -1 || u.indexof('mac') > -1,
   ipad: u.indexof('ipad') > -1,
   webapp: u.indexof('safari') == -1
  }
 } (),
 language:(navigator.browserlanguage || navigator.language).tolowercase()
};
document.writeln("语言版本: "+browser.language+"</br>");
document.writeln(" 是否为移动终端: "+browser.versions.mobile+"</br>");
document.writeln(" ios终端: "+browser.versions.ios+"</br>");
document.writeln(" android终端: "+browser.versions.android+"</br>");
document.writeln(" 是否为iphone: "+browser.versions.iphone+"</br>");
document.writeln(" 是否ipad: "+browser.versions.ipad+"</br>");
document.writeln(navigator.useragent+"</br>");

完整版,运用于项目代码

/*
*
* 判断pc端与wap端
*/
var mobile_bs = {
 versions: function() {
  var u = navigator.useragent;
  return {
   trident: u.indexof('trident') > -1, //ie内核
   presto: u.indexof('presto') > -1, //opera内核
   webkit: u.indexof('applewebkit') > -1, //苹果、谷歌内核
   gecko: u.indexof('gecko') > -1 && u.indexof('khtml') == -1, //火狐内核
   mobile: !! u.match(/applewebkit.*mobile.*/) || !! u.match(/applewebkit/) && u.indexof('qihu') && u.indexof('qihu') > -1 && u.indexof('chrome') < 0, //是否为移动终端
   ios: !!u.match(/\(i[^;]+;( u;)? cpu.+mac os x/), //ios终端
   android: u.indexof('android') > -1 || u.indexof('linux') > -1, //android终端或者uc浏览器
   iphone: u.indexof('iphone') > -1 || u.indexof('mac') > -1, //是否为iphone或者qqhd浏览器
   ipad: u.indexof('ipad') > -1,  //是否ipad
   webapp: u.indexof('safari') == -1 //是否web应该程序,没有头部与底部
  }
 } ()
};
if (mobile_bs.versions.mobile) {
 if (mobile_bs.versions.android || mobile_bs.versions.iphone || mobile_bs.versions.ipad || mobile_bs.versions.ios) {
  window.location.href = "移动端网址";
 }
}; 

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!