关于移动端解决键盘遮挡input的解决方案

我是利用scrollIntoView()方法来解决这个问题的,代码

let clientHeight = document.body.clientHeight;
  let _focusElem = null; //输入框焦点
  //利用捕获事件监听输入框等focus动作
  document.body.addEventListener("focus", function(e) {
    _focusElem = e.target || e.srcElement
  }, true);
  //因为存在软键盘显示而屏幕大小还没被改变,所以以窗体(屏幕显示)大小改变为准
  window.addEventListener("resize", function() {
    if (_focusElem && document.body.clientHeight < clientHeight) {
      //焦点元素滚动到可视范围的底部(false为底部)
      _focusElem.scrollIntoView(false)
    }
  });
scrollIntoView()这个方法有一个参数是类型Boolean,默认false, 如果为false输入框沿底部显示,为true则沿顶部显示

猜你喜欢

转载自www.cnblogs.com/bozhiyao/p/9034841.html