【js实现pc版网页自动识别手机号】js实现PC版网页自动识别手机客户端并跳转

更新时间:2019-09-15    来源:js教程    手机版     字体:

【www.bbyears.com--js教程】


PC版网页自动识别手机客户端并跳转,用js进行判断是否手机客户端进行跳转最好,特别是静态网页,把这个过程通过js的方式放在用户客户端执行,可以大大减少服务器端额外处理的压力。但是有时需要通过在服务器端进行判断的情况除外。

以腾讯网适配js函数为例:

<script>
(function(){
/*
  腾讯网适配跳转
*/
var reWriteUrl = function(url){
 if(url){
if(url.indexOf("/a/")>0 ){
 var Splits = url.split("/"),siteName=Splits[2].split("qq.com")[0].split(".").length==3?siteName=Splits[2].split("qq.com")[0].split(".")[0]+"_"+Splits[2].split("qq.com")[0].split(".")[1]:siteName=Splits[2].split("qq.com")[0].split(".")[0],aids=url.split("/a/")[1].split(".htm")[0].replace(/[^0-9]/g, ""),site="";
 if(typeof siteName!=="undefined" && typeof aids!=="undefined"){
if(siteName.split(".").length>2){
 var len = siteName.split(".").length;
 for(var i=0;i  site+=siteName.split(".")[i];
 if(i site+="_";
 }
 }
}else{
 site=siteName.split(".")[0];
}
return "http://xw.qq.com/"+siteName+"/"+aids;
 }
}
 }
};
var goToMobile = function(){
var Aarry = document.getElementsByTagName("a"),TmpArray=[];
for(var i=0;i  TmpArray[i]=Aarry[i].href.toString();
 if(TmpArray[i].split("/")[3]=="a"){
Aarry[i].href=reWriteUrl(TmpArray[i]);
 }
}

}
var mobileSietList={news:"news",photo:"photo",video:"video",view:"huati",finance:"finance",ent:"ent",sports:"sports",digi:"digi",mil:"mil",lady:"lady",auto:"auto",games:"games",house:"house",astro:"astro",cul:"cul",fashion:"fashion","2014":"shijiebei"};

if(/Android|webOS|iPhone|Windows Phone|iPod|BlackBerry|SymbianOS/i.test(navigator.userAgent)){
 /*底层页跳转*/
 var url=window.location.href;
 var pathname=window.location.pathname;
 if(url.indexOf("/a/")>0 && window.location.hostname!="www.nanjing2014.org"){
if(url.indexOf("?pc")<0){
try{
 window.location.href=reWriteUrl(url);
}catch(e){}
}
 }else{ // 频道首页跳转
if(url.indexOf("?mobile")<0){
 var mobileUrl=window.location.hostname.split(".")[0];
 if(/news|pp|video|view|finance|ent|sports|digi|mil|fashion|auto|games|house|astro|cul|2014/i.test(mobileUrl)){
try{
 window.location.href="http://xw.qq.com/m/"+mobileSietList[mobileUrl]+"/index.htm";
}catch(e){ 
}
 }
}
 }
 try{
//document.addEventListener("DOMContentLoaded", goToMobile, false);
 }catch(e){ 
 }
}
})();
 
</script>

以上函数取自腾讯网的js适配跳转,可以参考它的逻辑根据自己网站的情况实现这个过程。

本文来源:http://www.bbyears.com/wangyezhizuo/67960.html