1. 判斷瀏覽器類型
瀏覽器判斷使用的github開源項目current-device,下面是地址:
https://github.com/matthewhudson/current-device
在瀏覽器中可以使用下面地址進行瀏覽器引入,但是加載速度慢,不建議使用,我這里是直接下載本地。
<script src="https://unpkg.com/current-device/umd/current-device.min.js"></script>
2. 根據瀏覽器跳轉到對應的頁面
這是我的項目結構:
│ about_us.html
│ index.html
├─js
│ current-device.min.js
│ defalut.js
└─mobile
about_us.html
index.html
其實只要把移動端頁面放在mobile目錄下即可,然后需要在每個頁面(PC端和移動端)引入current-device.min.js和defalut.js,然后瀏覽器訪問時,執行defalut.js的方法進行跳轉。
defalut.js內容如下:
// 判斷瀏覽器類型,跳轉到對應的頁面
if (device.mobile() && !location.pathname.startsWith("/mobile")) {
window.location.href = location.protocol + "//" + location.host + "/mobile" + location.pathname + location.search;
} else if (device.windows() && location.pathname.startsWith("/mobile")) {
let pathname = location.pathname;
let pcpath = pathname.substring(("/mobile".length), pathname.length);
window.location.href = location.protocol + "//" + location.host + pcpath + location.search;
}
defalut.js主要是根據當前瀏覽器的類型來增加和刪除子目錄,在移動端時,我就判斷路徑是否以 “mobile” 開頭,不是我就在中間插入 “/mobile” ,在PC端同樣如此操作。
