JS如何实现网站中PC端和手机端自动识别并跳转对应的代码

1.  代码场景:

描述:在项目中,一般我们会使用响应式布局的方式或者借助bootstrap等插件来做响应式的网站。但是根据业务的需求,手机端可能会在功能上精简很多,我们也会写两套代码,分别用来实现PC端和手机端的功能。此时,就存在一个问题。项目在部署的时候只会使用一个地址,不会针对手机和PC端代码分别进行部署。这个时候就需要我们通过去识别视口分辨率的大小,来自动去跳转对应的代码。

2. 实现方式:

目前网上有很多的方法用来实现PC端和手机端的代码跳转,但我只用了一种实现方式。其他的暂时还没有尝试,希望可以跟大家学到更多的解决方案。在此特别感谢<<--老蒋部落-->>的方法给予了我很大的帮助。

此处贴出当前的JS代码:

<script type="text/javascript">
 
 function mobilePcRedirect() {
 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) {
  window.location.href= '手机端跳转页面URL';
 } else {
  window.location= 'PC端跳转页面URL';
 }
 };
 
 mobilePcRedirect();
 
</script>

将此方法分别写在手机端和PC端公共的Common.js中,然后在对应位置写入对应的路径即可。

例如:手机端公共JS中代码如下

// 实现网站自动跳转电脑PC端与手机端不同页面
function mobilePcRedirect() {
 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) {
 console.log("手机端跳转页面URL");
 } else {
 console.log("PC端跳转页面URL"); 
    // 注:此时写入的是PC端首页跳转路径
   window.location.href = getBasePath() + "/education/new_index.html";
 }
};
mobilePcRedirect();

反之,PC端公共JS中同样的写法即可。

3. 拓展内容(如何获取项目的根路径?)

获取项目名称:

/**
 * 获取项目名称 如:/video_learning
 **/
 
function getProjectName() {
 var strPath = window.document.location.pathname;
 var postPath = strPath.substring(0,strPath.substr(1).indexOf('/')+1);
 return postPath;
}

获取项目全路径:

/**
 * 获取项目全路径 如:http://localhost:8080/video_learning
 * */
 
function getBasePath(){
 //获取当前网址
 var curWwwPath=window.document.location.href;
 
 //获取主机地址之后的目录
 var pathName=window.document.location.pathname;
 var pos=curWwwPath.indexOf(pathName);
 
 //获取地址到端口号
 var localhostPath=curWwwPath.substring(0,pos);
 
 //项目名
 var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1); 
 return (localhostPath+projectName);
}

本次分享已完成,大家若有更好的方法或者意见欢迎指正学习。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持来客网。