js -- 移动端pc端自动切换
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                js -- 移动端pc端自动切换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                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 └─mobileabout_us.htmlindex.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端同樣如此操作。
轉載于:https://www.cnblogs.com/lixingwu/p/11439575.html
總結
以上是生活随笔為你收集整理的js -- 移动端pc端自动切换的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: shell判断IP地址是否合法
 - 下一篇: idea基于spring boot的依赖