APP内软键盘遮挡输入框解决方案

APP内软键盘遮挡输入框解决方案:
1、IOS无法弹起表现偶发,整体效果可接受;
2、Android上分X5内核和原生内核分别处理,但在收起键盘时未展开,表现为键盘弹起状态,故需要重新设置样式;
3、X5内核监听resize事件,重新设置样式触发页面绘制;
4、原生内核只触发了一次resize方法(猜测是webview团队对其进行了拦截),故需要依靠端提供的方案 addListentNewHeightCallback 进行样式设置;

/**
 * 监听输入框的软键盘弹起和收起事件,并执行页面样式和滚动操作
 */
export const keyboardDeal = () => {
  // 软键盘处理
  let timer1: number | undefined
  let timer2: number | undefined
  let keyboardHeight = 0
  const originHeight = window.screen.availHeight
 
  function listenKeyboard () {
    if (isIOS()) {
      // IOS 键盘:通过判断获取焦点的元素是否为输入框,得知键盘弹出状态(键盘收起时,同时失去焦点)
      // TODO: 由于IOS webview大小未修改,故修改样式也无效果
      // window.addEventListener('focusin', (e) => {
      //   // @ts-ignore 需要考虑元素属性 contenteditable disabled等
      //   if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') {
      //     keyboardPopup(e.target)
      //   } else {
      //     keyboardStowed(e.target)
      //   }
      // }, { passive: false })
    } else {
      // Andriod 键盘:Andriod 键盘弹起或收起页面高度会发生变化,以此为依据获知键盘收起
      window.addEventListener('resize', function () {
        const resizeHeight = window.innerHeight
        if (resizeHeight < originHeight) {
          keyboardPopup(document.activeElement)
        } else {
          keyboardStowed(document.activeElement)
        }
      }, false)
    }
  }
  listenKeyboard()
 
  // 键盘弹出
  function keyboardPopup (ele: any) {
    timer1 = setInterval(() => {
      const newKeyboardHeight = originHeight - window.innerHeight
      if (keyboardHeight !== newKeyboardHeight) {
        keyboardHeight = newKeyboardHeight
        return
      }
      if (keyboardHeight > 0) {
        clearInterval(timer1)
        document.documentElement.style.height = window.innerHeight + 'px'
        ele.scrollIntoViewIfNeeded(true)
      }
    }, 100)
  }
 
  // 键盘收起
  function keyboardStowed (ele: any) {
    timer2 = setInterval(() => {
      keyboardHeight = originHeight - window.innerHeight
      if (keyboardHeight === 0) {
        clearInterval(timer2)
        document.documentElement.style.height = '100%'
        document.documentElement.scrollTo(0, window.innerHeight)
        // ele.scrollIntoViewIfNeeded(true)
      }
    }, 100)
  }
 
  // 原生回调监听键盘展开收起(该方法仅在Android手APP内且下载x5内核失败的情况下调用)
  window.addListentNewHeightCallback = (height: number) => {
    // 适配逻辑
    const inputEle = document.activeElement
    if (window.innerHeight > height) {
      document.documentElement.style.height = height + 'px'
      inputEle && inputEle.scrollIntoView()
    } else {
      document.documentElement.style.height = '100%'
    }
  }
}

你可能感兴趣的:(javascript)