萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> 互動設計

移動端/PC 端自適應跳轉 JavaScript 實現全解析

WAP/3G 站點需根據訪問設備自動跳轉:手機/iPad 訪問 PC 站 → 跳轉移動端;PC 訪問移動端 → 留守或跳 PC 站。核心邏輯:navigator.platform + navigator.appVersion 雙重檢測,覆蓋主流移動設備。附完整代碼與部署指南。

核心檢測邏輯

  1. 平台標識檢測:匹配 navigator.platform 對已知移動端標識數組(iPhone, iPod, iPad, android, Nokia, SymbianOS, Windows Phone, Linux armv71, MAUI, BlackBerry, IEMobile 等)
  2. iPad 特判:部分 iPad 平台標識不含關鍵字,單獨 indexOf('iPad') 兜底
  3. Android 細分:內核同為 Linux,需結合 navigator.appVersion 匹配 /linux/i 並排除 X11(UC 瀏覽器平台),再匹配 /mobile/i 確認為移動端

完整部署代碼

<script language="JavaScript">
function mobile_device_detect(url) {
    var thisOS = navigator.platform;
    var os = ["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;
        }
    }
    // iPad 兜底
    if (navigator.platform.indexOf('iPad') != -1) {
        window.location = url;
    }
    // Android 細分
    var check = navigator.appVersion;
    if (check.match(/linux/i)) {
        if (check.match(/mobile/i) || check.match(/X11/i)) {
            window.location = url;
        }
    }
}
// 工具函數:in_array
Array.prototype.in_array = function(e) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == e) return true;
    }
    return false;
}
mobile_device_detect("https://www.heimaoseojishu.com"); // 替換為你的移動端域名
</script>

部署說明

  • 將代碼置於 PC 站 <head> 或 <footer> 區域
  • mobile_device_detect() 參數替換為目標移動端網址
  • 測試覆蓋:iPhone/iPod/iPad/Android/Nokia/Symbian/Windows Phone/BlackBerry/UC 瀏覽器等主流設備/瀏覽器

進階建議

  • 現代項目推薦採用響應式設計或服務端 User-Agent 判斷,避免客戶端跳轉閃屏與 SEO 風險
  • 若必須客戶端跳轉,增加 sessionStorage 標記防止重定向循環
  • 考慮 navigator.userAgent 正則匹配作為補充,覆蓋率更高

代碼經大部分移動設備實測,識別準確、跳轉正確。舊項目快速適配首選,新項目請優先考慮響應式架構。

copyright © 萬盛學電腦網 all rights reserved