這篇文章將為大家詳細講解有關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);
}關于“JS怎么實現網站中PC端和手機端自動識別并跳轉對應的代碼”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。