需求
移动端表单下一步需要定位在最下方,但是在键盘弹起时想要按钮不顶上来
尝试解决
方案一:focusin/focusout
- 问题: android手机键盘有个隐藏按钮,点击之后收起键盘(图一),但是光标还在输入框内(图二),没有触发focusout事件,并且会出现按钮一闪而过的情况,加动画页不好使,因此android不可行,但是ios没有问题
图一
图二
方案二:window.onresize
- 问题:ios键盘弹起时把页面向上推了,因此没有触发window.onresize事件,因此在ios上不生效,但是android时没有问题的
总结
由于以上两种情况,所以判断系统是android或者是ios,分别判断,代码如下:
// 获取屏幕高度
const windowHeight = document.documentElement.clientHeight ||document.body.clientHeight;
const [ height, setHeight] = useState(windowHeight);
// 获取手机类型
let u = navigator.userAgent;
let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
// 如果是ios,使用focusin/focusout判断
if(isiOS) {
document.body.addEventListener('focusin', () => {
setIsKeyIn(true)
})
document.body.addEventListener('focusout', () => {
setIsKeyIn(false)
})
}else {
// android则可以使用window.onresize
window.onresize = () => {
return (() => {
if(windowHeight > document.body.clientHeight) {
setIsKeyIn(true)
}else {
setIsKeyIn(false)
}
setHeight(document.body.clientHeight)
})()
}
}