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()
}