1. 程式人生 > 程式設計 >JS如何實現網站中PC端和手機端自動識別並跳轉對應的程式碼

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);
}

本次分享已完成,大家若有更好的方法或者意見歡迎指正學習。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。