关于几个移动端软键盘的坑及其解决方案

一、IOS 键盘弹起挡住原来的视图

能够经过监听移动端软键盘弹起javascript

window.addEventListener('resize', function() {
  if (
    document.activeElement.tagName === 'INPUT' ||
    document.activeElement.tagName === 'TEXTAREA'
  ) {
    window.setTimeout(function() {
      if ('scrollIntoView' in document.activeElement) {
        document.activeElement.scrollIntoView(false)
      } else {
        document.activeElement.scrollIntoViewIfNeeded(false)
      }
    }, 0)
  }
})
复制代码

二、onkeyUp 和 onKeydown 兼容性问题

IOS 中 input 键盘事件 keyup、keydown、等支持不是很好, 用 input 监听键盘 keyup 事件,在安卓手机浏览器中没有问题,可是在 ios 手机浏览器中用输入法输入以后,并未马上相应 keyup 事件css

三、IOS12 输入框难以点击获取焦点,弹不出软键盘

定位找到问题是 fastclick.js 对 IOS12 的兼容性,可在 fastclick.js 源码或者 main.js 作如下修改html

FastClick.prototype.focus = function(targetElement) {
  var length
  if (
    deviceIsIOS &&
    targetElement.setSelectionRange &&
    targetElement.type.indexOf('date') !== 0 &&
    targetElement.type !== 'time' &&
    targetElement.type !== 'month'
  ) {
    length = targetElement.value.length
    targetElement.setSelectionRange(length, length)
    targetElement.focus()
  } else {
    targetElement.focus()
  }
}
复制代码

四、IOS 键盘收起时页面没用回落,底部会留白

经过监听键盘回落时间滚动到原来的位置java

window.addEventListener('focusout', function() {
  window.scrollTo(0, 0)
})

//input输入框弹起软键盘的解决方案。
var bfscrolltop = document.body.scrollTop
$('input')
  .focus(function() {
    document.body.scrollTop = document.body.scrollHeight
    //console.log(document.body.scrollTop);
  })
  .blur(function() {
    document.body.scrollTop = bfscrolltop
    //console.log(document.body.scrollTop);
  })
复制代码

五、IOS 下 fixed 失效的缘由

软键盘唤起后,页面的 fixed 元素将失效,变成了 absolute,因此当页面超过一屏且滚动时,失效的 fixed 元素就会跟随滚动了。不只限于 type=text 的输入框,凡是软键盘(好比时间日期选择、select 选择等等)被唤起,都会遇到一样地问题。ios

解决方法: 不让页面滚动,而是让主体部分本身滚动,主体部分高度设为 100%,overflow:scrollweb

<body>
  <div class='warper'>
    <div class='main'></div>
  <div>
  <div class="fix-bottom"></div>
</body>
复制代码
.warper {
  position: absolute;
  width: 100%;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch; /* 解决ios滑动不流畅问题 */
}
.fix-bottom {
  position: fixed;
  bottom: 0;
  width: 100%;
}
复制代码
相关文章
相关标签/搜索