如何做一个听话的“输入框”

604 阅读2分钟

在移动端的web开发中,一提起输入框,程序猿(媛)肯定有很多可以吐槽的点。尤其在现在许许多多的公司都要求开发h5项目,就避免不了输入框比较靠页面底部,输入框聚焦的时候键盘弹起就会挡住输入框。

1. ios键盘遮住输入框,如下图


2. 解决方案 : scrollIntoView 的应用,将input输入框显示在可视区域。

      if (/iphone|ipod|ipad/i.test(navigator.appVersion)) {
        let timer = null
        let timer2 = null
        document.addEventListener(
          'blur',
          e => {
            // 这里加了个类型判断,因为a等元素也会触发blur事件
            if (['input'].includes(e.target.localName)) {
              timer = setTimeout(() => {
                document.body.scrollIntoView(false)
                // scrollIntoView参数 true:元素的顶端将和其所在滚动区的可视区域的顶端对齐; false:底端对齐。
              }, 100)// 延时 == 键盘弹起需要时间
              clearTimeout(timer2)
            }
          },
          true
        )
        document.addEventListener(
          'focus',
          () => {
            // document.body.scrollIntoView(false)
            timer2 = setTimeout(() => {
              document.body.scrollIntoView(false)
            }, 100)
            clearTimeout(timer)
          },
          true
        )
      }

3. 结果与原理


最终实现的结果就是上图啦,原理就是element.scrollIntoView(alignToTop),alignToTop为true时与可视区域滚动区顶部对齐,false时与底部对齐,再由于键盘弹起需要时间所以我们加了100ms作为延迟再将输入框顶起到可视区域。

4. 缺陷

实现代码很简单,不过有点小缺陷:页面过长时,由于fixed失效,输入框依然也会跟着页面滑走。这时,我们需要一个固定的输入框,像上面的输入框我们可以flex或者fixed固定输入框。如果是下面的这种情况呢:


弹出层有输入框,我们可以将body进行fixed即可。

 //弹出层出现时,将body定位设置为fixed
    fixedBody() {
      var scrollTop =document.body.scrollTop ||document.documentElement.scrollTop
      document.body.style.cssText += 'position:fixed;top:-' + scrollTop + 'px;'
    },
  //弹出层消失时,将body定位设置为空
    looseBody() {
      var body = document.body
      body.style.position = ''
      var top = body.style.top
      document.body.scrollTop = document.documentElement.scrollTop = -parseInt(
        top
      )
      body.style.top = ''
    }