根據不同訪問裝置跳轉到PC頁面或手機頁面
阿新 • • 發佈:2019-01-10
目前很多網站都是採用了響應式自適應頁面的設計了,根據訪問裝置的不同,顯示不同的內容。但是還是會有一些節奏比較慢的網站,還是PC頁面和手機PAD頁面不同的訪問域名。正好我這裡有個需要,同一個域名要根據不同的訪問裝置顯示PC頁面或者手機頁面,這裡收集兩個比較簡潔的方法,都是通過JS程式碼實現的。
第一個:
<script type="text/javascript">
var userAgent = navigator.userAgent.toLowerCase();
var platform;
if(userAgent == null || userAgent == '' ){
platform = 'WEB' ;
}else{
if(userAgent.indexOf("android") != -1 ){
platform = 'ANDROID';
location.href = "http://m.kuegou.com/";
}else if(userAgent.indexOf("ios") != -1 || userAgent.indexOf("iphone") != -1 || userAgent.indexOf("ipad") != -1){
platform = 'IOS' ;
location.href = "http://m.kuegou.com/";
}else if(userAgent.indexOf("windows phone") != -1 ){
platform = 'WP';
location.href = "http://m.kuegou.com/";
}else{
platform = 'WEB' ;
location.href = "http://www.kuegou.com/";
}
}
</script>
直接上程式碼,修改程式碼中你的PC頁面和手機頁面地址即可。
第二個:
這一個是兩段程式碼,分別放到PC頁面網頁和手機頁面網頁,實現不同裝置訪問不同頁面都能實現調整,比如電腦訪問了手機頁面的地址也會跳轉到PC頁面上來。
首先是放入PC頁面的程式碼:
<script type="text/javascript">
var url = window.location.pathname;
var wapurl="http://3g.xxx.com"+url
if(/AppleWebKit.*Mobile/i.test(navigator.userAgent) || (/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/.test(navigator.userAgent))){
if(window.location.href.indexOf("?mobile")<0){
try{
if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)){
window.location.href=wapurl;
}else{
window.location.href=wapurl;
}
}catch(e){}
}
}
</script>
下邊是放入手機頁面的程式碼:
<script type="text/javascript">
var url = window.location.pathname;
var pcurl="http://www.xxx.com"+url
if(/AppleWebKit.*Mobile/i.test(navigator.userAgent)==false || (/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/.test(navigator.userAgent))==false){
if(window.location.href.indexOf("?mobile")<0){
try{
if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)==false){
window.location.href=pcurl;
}
}catch(e){}
}
}
</script>