关于javascript:APP内软键盘遮挡输入框解决方案

44次阅读

共计 1960 个字符,预计需要花费 5 分钟才能阅读完成。

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%'}
  }
}

正文完
 0