JS如何实现网站中PC端和手机端自动识别并跳转对应的代码
1. 代码场景:
描述:在项目中,一般我们会使用响应式布局的方式或者借助bootstrap等插件来做响应式的网站。但是根据业务的需求,手机端可能会在功能上精简很多,我们也会写两套代码,分别用来实现PC端和手机端的功能。此时,就存在一个问题。项目在部署的时候只会使用一个地址,不会针对手机和PC端代码分别进行部署。这个时候就需要我们通过去识别视口分辨率的大小,来自动去跳转对应的代码。
2.实现方式:
目前网上有很多的方法用来实现PC端和手机端的代码跳转,但我只用了一种实现方式。其他的暂时还没有尝试,希望可以跟大家学到更多的解决方案。在此特别感谢<<--老蒋部落-->>的方法给予了我很大的帮助。
此处贴出当前的JS代码:
functionmobilePcRedirect(){ varsUserAgent=navigator.userAgent.toLowerCase(); varbIsIpad=sUserAgent.match(/ipad/i)=="ipad"; varbIsIphoneOs=sUserAgent.match(/iphoneos/i)=="iphoneos"; varbIsMidp=sUserAgent.match(/midp/i)=="midp"; varbIsUc7=sUserAgent.match(/rv:1.2.3.4/i)=="rv:1.2.3.4"; varbIsUc=sUserAgent.match(/ucweb/i)=="ucweb"; varbIsAndroid=sUserAgent.match(/android/i)=="android"; varbIsCE=sUserAgent.match(/windowsce/i)=="windowsce"; varbIsWM=sUserAgent.match(/windowsmobile/i)=="windowsmobile"; if(bIsIpad||bIsIphoneOs||bIsMidp||bIsUc7||bIsUc||bIsAndroid||bIsCE||bIsWM){ window.location.href='手机端跳转页面URL'; }else{ window.location='PC端跳转页面URL'; } }; mobilePcRedirect();
将此方法分别写在手机端和PC端公共的Common.js中,然后在对应位置写入对应的路径即可。
例如:手机端公共JS中代码如下
//实现网站自动跳转电脑PC端与手机端不同页面 functionmobilePcRedirect(){ varsUserAgent=navigator.userAgent.toLowerCase(); varbIsIpad=sUserAgent.match(/ipad/i)=="ipad"; varbIsIphoneOs=sUserAgent.match(/iphoneos/i)=="iphoneos"; varbIsMidp=sUserAgent.match(/midp/i)=="midp"; varbIsUc7=sUserAgent.match(/rv:1.2.3.4/i)=="rv:1.2.3.4"; varbIsUc=sUserAgent.match(/ucweb/i)=="ucweb"; varbIsAndroid=sUserAgent.match(/android/i)=="android"; varbIsCE=sUserAgent.match(/windowsce/i)=="windowsce"; varbIsWM=sUserAgent.match(/windowsmobile/i)=="windowsmobile"; 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 **/ functiongetProjectName(){ varstrPath=window.document.location.pathname; varpostPath=strPath.substring(0,strPath.substr(1).indexOf('/')+1); returnpostPath; }
获取项目全路径:
/** *获取项目全路径如:http://localhost:8080/video_learning **/ functiongetBasePath(){ //获取当前网址 varcurWwwPath=window.document.location.href; //获取主机地址之后的目录 varpathName=window.document.location.pathname; varpos=curWwwPath.indexOf(pathName); //获取地址到端口号 varlocalhostPath=curWwwPath.substring(0,pos); //项目名 varprojectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1); return(localhostPath+projectName); }
本次分享已完成,大家若有更好的方法或者意见欢迎指正学习。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。