【解决方案】安卓端H5,点击输入框时,软键盘遮挡输入框

260 阅读1分钟

最近在开发中,遇到了一个安卓端webview(H5),输入框获取焦点时,输入框被安卓的软键盘遮挡住的问题。 以下是解决方案的代码:

      /**
       * 节流函数
       */
      function throttle(func, wait) {
        var timer = null;
        return function () {
            var _this = this;
            var args = arguments;
            if (!timer) {
                timer = setTimeout(function () {
                    timer = null;
                    func.apply(_this, args)
                }, wait)
            }
        }
      }
      /**
       * 输入框滚入可视区域
       */ 
      function activeElementScrollIntoView() {
        const activeEl = document.activeElement;
        if (
          activeEl.tagName === 'INPUT' || 
          activeEl.tagName === 'TEXTAREA'
        ) {
          window.setTimeout(() => {
            activeEl.scrollIntoViewIfNeeded();
          }, 0);
        }
      }
      // 安卓端,输入框获取焦点时,自动滚入可见区域
      window.addEventListener('resize', throttle(activeElementScrollIntoView, 250))