1. 程式人生 > >JavaScript判斷裝置型別載入對應網頁並設定兩端通用事件

JavaScript判斷裝置型別載入對應網頁並設定兩端通用事件

JavaScript如何判斷裝置型別載入對應網頁並設定通用事件

基本思路:

在網頁入口新增判斷邏輯,如下:首先獲取當前navigator物件的userAgent,通過userAgent判斷當前裝置型別。

①:如果符合移動端判斷邏輯,則載入移動端入口;否則載入pc端入口

②:通用事件的設定,比如點選事件,PC端為click,但是移動端也用click的話分不清是長按還是點選;根據平臺型別設定通用事件,可以在寫觸發函式時不用每次都判斷。

舉個例子:如下圖,點選語言選擇按鈕彈出語言選擇框,用click事件的話,PC端沒有什麼問題,但是移動端的話長按時不應該彈出,應該手指離開時再顯示。這時我們可以給window定義一個事件,比如clickEvent,在當前頁面下載時設定這個clickEvent對應的正確的事件。在寫觸發函式時就不必判斷當前裝置型別。

設定clickEvent後實現上邊需求的原始碼:

        $('.select-language').on(clickEvent, () => {
            $('.language-pop').fadeIn()
        })

JavaScript判斷裝置型別載入對應網頁並設定通用事件原始碼:

      (function(){
          var userAgent = window.navigator.userAgent;
          var ua = userAgent.toLowerCase();
          var platform = {
                isAndroid: function() {
                    return ua.indexOf("android") > -1;
                },
                isIOS: function() {
                    return ua.indexOf("iphone") > -1;
                },
                isWinPhone: function() {
                    return !!navigator.userAgent.match(/Windows Phone/i);
                },
                isIpad : function(){
                    return ua.indexOf("ipad") > -1;
                },
                isPhone: function() {
                    return this.isAndroid() || this.isIOS() || this.isWinPhone() || this.isIpad();
                }
          }
          if(!platform.isPhone()){
              window.location.href = window.location.href.replace("mobile.html","pc.html");
          }
          window.isPhone = platform.isPhone();
          window.clickEvent = isPhone ? 'touchend':'click';
          window.moveEvent = isPhone ? 'touchmove':'mousemove';
          window.clickStart = isPhone? 'touchstart' : 'mousedown';
          window.clickEnd = isPhone? 'touchend' : 'mouseup';
      })();