4G 普及之後,行動端的流量早已壓過電腦版,很多網站乾脆電腦版與手機版官網並存。剩下的問題是:怎麼讓用手機開啟電腦版網址的人,自動被導引到行動版?下面兩種做法各有適用場景。
直接檢查 userAgent 是否命中 iPad、iPhone OS、Android 或 Windows Mobile,命中就跳。程式碼短、直覺,適合行動版與電腦版內容對應固定的情況。
復制代碼 代碼如下:
<script type="text/javascript">
(function(){
var ua = navigator.userAgent.toLowerCase();
var bIsIpad = ua.match(/ipad/i) == "ipad";
var bIsIphoneOs = ua.match(/iphone os/i) == "iphone os";
var bIsAndroid = ua.match(/android/i) == "android";
var bIsWM = ua.match(/windows mobile/i) == "windows mobile";
if (bIsIpad || bIsIphoneOs || bIsAndroid || bIsWM) {
window.location.href = "https://m.jb51.net/android/game/826.html";
}
})();
</script>
這一段涵蓋的裝置清單更廣,並額外處理了兩個歷史難題:一是部分手機平台的 navigator.platform 資訊不明,二是 Android 內核同樣是 Linux,導致平台欄位顯示混亂,需要再從 navigator.appVersion 下手。
<SCRIPT LANGUAGE="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("https://***.***.com");
</SCRIPT>
備註:mobile_device_detect() 裡那個網址,記得換成你自己的行動版網站位址。
兩種做法的取捨很清楚:方法一簡潔,但裝置清單要自己維護;方法二覆蓋面廣、對舊型手機與特殊瀏覽器更寬容,代價是程式碼長得多。若網站有後端,其實更穩妥的方式是搭配使用者代理的伺服器端判斷,避免前端跳轉多繞一圈。