如何使用JS來判斷裝置是pc還是移動?
阿新 • • 發佈:2019-01-10
方法一:純 JS 判斷
使用這方法既簡單,又實用,不需要引入 jQuery 庫,把以下程式碼加入到 <head> 裡即可。
- <script type=”text/javascript”>
- if(/iphone|ipod|ipad|ipad|Android|nokia|blackberry|webos|webos|webmate|bada|lg|ucweb|skyfire|sony|ericsson|mot|samsung|sgh|lg|philips|panasonic|alcatel|lenovo|cldc|midp|wap|mobile/i.test(navigator.userAgent.toLowerCase())){
- window.location = “mobile.html”; //可以換成 http 地址
- }
- </script>
方法二:使用 Device.Js 庫
device.js 是一個用於檢查裝置用的外掛,使用它你可以很方便的判斷裝置的作業系統,以及裝置是縱向還是橫向。
首先,我們下載 Device.js,並引入 Device.js 檔案。
STEP 1: 引入 JS 檔案
- <script src=”device.min.js”></script>
STEP 2: 加入判斷程式碼
- <script type=”text/javascript”>
- if(device.mobile()){
- window.location = “shouji.html”; //可以換成 http 地址
- }
- </script>