h5軟鍵盤兼容方案


本人在做公司項目的時候,在h5上調用鍵盤,發現了許多問題,主要問題總結如下

1.在 Android 和 IOS 上,鍵盤彈出收起在頁面 webview 里表現不同。

// 判斷設備類型
var judgeDeviceType = function () {
  var ua = window.navigator.userAgent.toLocaleLowerCase();
  var isIOS = /iphone|ipad|ipod/.test(ua);
  var isAndroid = /android/.test(ua);

  return {
    isIOS: isIOS,
    isAndroid: isAndroid
  }
}()

// 監聽輸入框的軟鍵盤彈起和收起事件
function listenKeybord($input) {
  if (judgeDeviceType.isIOS) {
    // IOS 鍵盤彈起:IOS 和 Android 輸入框獲取焦點鍵盤彈起
    $input.addEventListener('focus', function () {
      console.log('IOS 鍵盤彈起啦!');
      // IOS 鍵盤彈起后操作
    }, false)

    // IOS 鍵盤收起:IOS 點擊輸入框以外區域或點擊收起按鈕,輸入框都會失去焦點,鍵盤會收起,
    $input.addEventListener('blur', () => {
      console.log('IOS 鍵盤收起啦!');
      // IOS 鍵盤收起后操作
    })
  }

  // Andriod 鍵盤收起:Andriod 鍵盤彈起或收起頁面高度會發生變化,以此為依據獲知鍵盤收起
  if (judgeDeviceType.isAndroid) {
    var originHeight = document.documentElement.clientHeight || document.body.clientHeight;

    window.addEventListener('resize', function () {
      var resizeHeight = document.documentElement.clientHeight || document.body.clientHeight;
      if (originHeight < resizeHeight) {
        console.log('Android 鍵盤收起啦!');
        // Android 鍵盤收起后操作
      } else {
        console.log('Android 鍵盤彈起啦!');
        // Android 鍵盤彈起后操作
      }

      originHeight = resizeHeight;
    }, false)
  }
}

2.微信瀏覽器版本6.7.4+IOS12會出現鍵盤收起后,視圖被頂上去了沒有下來

console.log('IOS 鍵盤收起啦!');
// IOS 鍵盤收起后操作
// 微信瀏覽器版本6.7.4+IOS12會出現鍵盤收起后,視圖被頂上去了沒有下來
var wechatInfo = window.navigator.userAgent.match(/MicroMessenger\/([\d\.]+)/i);
if (!wechatInfo) return;

var wechatVersion = wechatInfo[1];
var version = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);

if (+wechatVersion.replace(/\./g, '') >= 674 && +version[1] >= 12) {
  setTimeout(function () {
    window.scrollTo(0, Math.max(document.body.clientHeight, document.documentElement.clientHeight));
  })
}

3.鍵盤滾動導致遮擋輸入框

1.在 IOS 上,會將 webview 整體往上滾一段距離,使得該獲取焦點的輸入框自動處於可視區,而在 Android 則不會這樣,它只會改變頁面高度,而不會去滾動到當前焦點元素到可視區。

2.由於上面已經實現監聽 IOS 和 Android 鍵盤彈起和收起,在這里,只需在 Android 鍵盤彈起后,將焦點元素滾動到可視區即可


// 獲取到焦點元素滾動到可視區
function activeElementScrollIntoView(activeElement, delay) {
  var editable = activeElement.getAttribute('contenteditable')

  // 輸入框、textarea或富文本獲取焦點后沒有將該元素滾動到可視區
  if (activeElement.tagName == 'INPUT' || activeElement.tagName == 'TEXTAREA' || editable === '' || editable) {
    setTimeout(function () {
      activeElement.scrollIntoView();
    }, delay)
  }
}

// ...
// Android 鍵盤彈起后操作
activeElementScrollIntoView($input, 1000);
// ...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM