van-popup 内input输入框被键盘遮挡问题

2,651 阅读1分钟

问题和解决方案

vue2.0 + vant2 开发h5,内嵌在手机app内部,在使用van-popup制作图1页面时,ios手机发现点击输入框,键盘弹起后,弹框的内容均在键盘后面,被完全挡住情况如图2

微信图片_20230908162405.jpg

图1

微信图片_20230908162356.jpg

图2

键盘完全遮挡住了验证码输入弹框,在网上查阅了很多资料我解决方案,尝试了很多种,最终发现只有以下方案可以解决最终的问题。在input输入框的focus事件中处理。代码如下
   let u = navigator.userAgent
       let isIos = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
       if (isIos) { // 只ios才走,安卓不需要处理
        document.body.addEventListener('focusin', () => {
          // 弹出键盘
          setTimeout(() => {
            console.log(document.activeElement.tagName)
            if (document.activeElement.tagName == 'INPUT') {
              // 键盘高度大概是302,因为我这个弹框高度写死的593px,为了保持和安卓一样的效果,所以加上了弹框整个高度
              document.getElementsByTagName('body')[0].style.height = (window.innerHeight + 593) + 'px'
              document.body.scrollTop = 593
            }
          })
        })
        document.body.addEventListener('focusout', () => {
          console.log('收起键盘')
          setTimeout(() => {
            window.scrollTo(0, 0)
            document.getElementsByTagName('body')[0].style.height = window.innerHeight + 'px';
          })
        })
       }

最终效果如下图

微信图片_20230908165040.jpg

ios效果

还有一些方案比如 document.activeElement.scrollIntoView(); document.activeElement.scrollIntoViewIfNeeded(); 这些均尝试了,在ios11上均不生效。