html 檢測用戶的手機是安卓還是ios,然後點擊分別跳轉到不同的頁面

在HTML頁面中直接檢測用戶的操作系統(Android或iOS)並根據結果跳轉到不同的頁面,通常需要藉助JavaScript來實現。下面是一個簡單的示例代碼,它通過檢測用戶代理字符串(User Agent)來判斷用戶的操作系統,並在點擊按鈕時根據操作系統跳轉到不同的頁面。

<!DOCTYPE html>
<html>
<head>
    <title>Device Redirect</title>
</head>
<body>

<button id="downloadButton">下載應用</button>

<script>
document.getElementById('downloadButton').onclick = function() {
    var userAgent = navigator.userAgent || navigator.vendor || window.opera;

    // 檢測iOS設備
    if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
        window.location.href = 'https://example.com/ios';
    }
    // 檢測Android設備
    else if (/android/i.test(userAgent)) {
        window.location.href = 'https://example.com/android';
    }
    // 其他設備
    else {
        window.location.href = 'https://example.com/other';
    }
};
</script>

</body>
</html>

這段代碼中的關鍵部分是document.getElementById('downloadButton').onclick函數,它會在用戶點擊按鈕時執行。腳本首先獲取用戶代理字符串,然後使用正則表達式檢查字符串中是否含有表示iOS或Android的關鍵詞。根據檢測結果,腳本將使用window.location.href將用戶重定向到相應的頁面。

請根據你的實際需求替換https://example.com/ioshttps://example.com/androidhttps://example.com/other這些URL。

發布者:彬彬筆記,轉載請註明出處:https://www.binbinbiji.com/zh-hant/html5/3195.html

(0)
彬彬筆記彬彬筆記
上一篇 2024年2月2日
下一篇 2024年2月22日

相關推薦

發表回復

登錄後才能評論
蜀ICP備14017386號-13