JS如何实现⽹站中PC端和⼿机端⾃动识别并跳转对应的
代码
1. 代码场景:
描述:在项⽬中,⼀般我们会使⽤响应式布局的⽅式或者借助bootstrap等插件来做响应式的⽹站。但是根据业务的需求,⼿机端可能会在功能上精简很多,我们也会写两套代码,分别⽤来实现PC端和⼿机端的功能。此时,就存在⼀个问题。项⽬在部署的时候只会使⽤⼀个地址,不会针对⼿机和PC端代码分别进⾏部署。这个时候就需要我们通过去识别视⼝分辨率的⼤⼩,来⾃动去跳转对应的代码。2. 实现⽅式:
⽬前⽹上有很多的⽅法⽤来实现PC端和⼿机端的代码跳转,但我只⽤了⼀种实现⽅式。其他的暂时还没有尝试,希望可以跟⼤家学到更多的解决⽅案。在此特别感谢<<--⽼蒋部落-->>的⽅法给予了我很⼤的帮助。此处贴出当前的JS代码:
将此⽅法分别写在⼿机端和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);}
本次分享已完成,⼤家若有更好的⽅法或者意见欢迎指正学习。
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。