适配安卓键盘挡住输入框

export const pageInputScroll = () => {



  let initWindowHeight = window.innerHeight;

  setTimeout(() => {

   let wrapDiv = document.getElementById('root');

   wrapDiv.style.minHeight = initWindowHeight+'px';

   }, 500);



   //由于我们不能直接知道软键盘什么时候出来,不过软键盘出来的时候窗口高度会缩小,所以我们可以通过监听窗口大小变化事件来判断软键盘是否弹出

  window.onresize=function(){ //如果浏览器窗口高度缩小25%以上,就认为是软键盘出来了

   if(initWindowHeight - window.innerHeight > initWindowHeight / 4 && document.querySelectorAll(':focus').length > 0) {

    let offsetObj = offset(document.querySelectorAll(':focus')[0]);

    if(offsetObj.top > initWindowHeight / 4) document.body.scrollTop = offsetObj.top - initWindowHeight / 4;

   } else if(window.innerHeight - initWindowHeight < 20) document.body.scrollTop = 0;

  };

 }



 function offset(element) {

  let offset = {

   top: 0,

   left: 0

  };

  let _position;



  getOffset(element, true);



  return offset;



  // 递归获取 offset, 可以考虑使用 getBoundingClientRect

  function getOffset(node, init) {

   // 非Element 终止递归

   if (node.nodeType !== 1) {

    return;

   }

   _position = window.getComputedStyle(node)['position'];



   // position=static: 继续递归父节点

   if (typeof(init) === 'undefined' && _position === 'static') {

    getOffset(node.parentNode);

    return;

   }

   offset.top = node.offsetTop + offset.top - node.scrollTop;

   offset.left = node.offsetLeft + offset.left - node.scrollLeft;

   // position = fixed: 获取值后退出递归

   if (_position === 'fixed') {

    return;

   }



   getOffset(node.parentNode);

  }

};

在项目初始化时

if(/Android/i.test(navigator.userAgent)){
    pageInputScroll()
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值