1. 程式人生 > >手機訪問PC網站自動跳轉到手機版

手機訪問PC網站自動跳轉到手機版

this 添加 手機系統 lastindex details 特殊 開發 pod windows

隨著智能手機的流行,4G時代來臨,手機用戶越來越多,在生活中甚至手機比電腦用的還多,當前開發的網站大都是PC和WAP版並存,但是很少有用戶願意去記住一個網站的兩個端的不同域名,所以需要我們做一些設置,在用戶訪問首頁的時候,進行分析跳轉,現將網上流行的幾種方式匯總如下,希望對大家有用:


第一種方式:
推薦,簡單易用,親測可以正常使用,代碼如下:

<script src="http://siteapp.baidu.com/static/webappservice/uaredirect.js" type="text/javascript"></script>
<script type="text/javascript">uaredirect("你的手機版網址");</script>


第二種方式:

添加js代碼,代碼如下:

<script type="text/javascript">
try {
var urlhash = window.location.hash;
if (!urlhash.match("fromapp")) {
if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iPad)/i))) {
window.location = "你的手機版地址";
}
}
}
catch (err) {
}
</script>



第三種方式:

添加js代碼,代碼如下:

<script type="text/javascript">
function urlredirect() {
var sUserAgent = navigator.userAgent.toLowerCase();
if ((sUserAgent.match(/(ipod|iphone os|midp|ucweb|android|windows ce|windows mobile)/i))) {
//PC跳轉移動端
var thisUrl = window.location.href;
//此處是在PC鏈接後自動添加手機版前綴,根據項目自行變更,我的是m開頭
window.location.href = thisUrl.substr(0,thisUrl.lastIndexOf(‘/‘) + 1) + ‘mobile/‘;
}
}
urlredirect();
</script>




第四種方式:

添加js代碼,代碼如下:

<script type="text/javascript">
function mobile_device_detect(url) {
var thisOS = navigator.platform;
var os = new Array("iPhone", "iPod", "iPad", "android", "Nokia",
"SymbianOS", "Symbian", "Windows Phone", "Phone",
"Linux armv71", "MAUI", "UNTRUSTED/1.0", "Windows CE",
"BlackBerry", "IEMobile");
for ( var i = 0; i < os.length; i++) {
if (thisOS.match(os[i])) {
window.location = url;
}
}
// 因為相當部分的手機系統不知道信息,這裏是做臨時性特殊辨認
if (navigator.platform.indexOf(‘iPad‘) != -1) {
window.location = url;
}
// 做這一部分是因為Android手機的內核也是Linux
// 但是navigator.platform顯示信息不盡相同情況繁多,因此從瀏覽器下手,即用navigator.appVersion信息做判斷
var check = navigator.appVersion;
if (check.match(/linux/i)) {
// X11是UC瀏覽器的平臺 ,如果有其他特殊瀏覽器也可以附加上條件
if (check.match(/mobile/i) || check.match(/X11/i)) {
window.location = url;
}
}
// 類in_array函數
Array.prototype.in_array = function(e) {
for (i = 0; i < this.length; i++) {
if (this[i] == e)
return true;
}
return false;
}
}
mobile_device_detect("你的手機版地址");
</script>



以上方式如有錯誤,歡迎指正!
---------------------
作者:異教徒的信仰
來源:CSDN
原文:https://blog.csdn.net/sinat_29356635/article/details/52814556
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

手機訪問PC網站自動跳轉到手機版