前言:H5开发过程中,软键盘弹起有时会出现遮挡Input输入框的问题,下面来看看解决方法。
方法一:onFocus + setTimeout + scrollIntoView【此方法更加简单】
<Input
placeholder=""
onFocus={(e) => {
setTimeout(() => {
e?.target?.scrollIntoView({ block: "center", behavior: "smooth" });
}, 400);
}}
/>;
方法二:useRef + useMonitorSoftKeyboard + onFocus + onBlur + setTimeout + scrollIntoView【此方法能适应更多情况】
useMonitorSoftKeyboard
:H5软键盘监听 Hooks —— 详情isInViewPort
方法:判断元素是否在可视区域;因为focus的时候可能会触发原来的顶上可视区域行为,我们只对没有被默认行为顶上且键盘弹起后还不在可视区的情况,进行scrollIntoView的操作;
import { useCallback, useRef } from 'react';
import { useMonitorSoftKeyboard } from './hooks';
import { Button, Form, Input } from 'antd-mobile';
const isInViewPort = element => {
const viewWidth = window.innerWidth || document.documentElement.clientWidth;
const viewHeight = window.innerHeight || document.documentElement.clientHeight;
const { top, right, bottom, left } = element.getBoundingClientRect();
return top >= 0 && left >= 0 && right <= viewWidth && bottom <= viewHeight;
};
const TestComp = () => {
const target = useRef<HTMLInputElement | null>(null);
const monitorSoftKeyboard = useCallback(param => {
if (!!param?.isUp && !!target.current) {
setTimeout(() => {
if (!isInViewPort(target.current)) target.current?.scrollIntoView({ block: 'center' });
}, 300);
}
}, []);
useMonitorSoftKeyboard({ callback: monitorSoftKeyboard });
return (
<div style={{ width: '100%', overflowY: 'auto', backgroundColor: 'aliceblue' }}>
<div style={{ height: '50vh' }} />
<Form
name='form'
onFinish={() => {}}
footer={
<Button block type='submit' color='primary' size='large'>
提交
</Button>
}
>
<Form.Item name='name1' label='姓名' rules={[{ required: true }]}>
<Input
placeholder='请输入姓名'
onFocus={e => {
target.current = e?.target;
}}
onBlur={() => {
target.current = null;
}}
/>
</Form.Item>
<Form.Item name='address1' label='地址' help='详情地址'>
<Input
placeholder='请输入地址'
onFocus={e => {
target.current = e?.target;
}}
onBlur={() => {
target.current = null;
}}
/>
</Form.Item>
<Form.Header>
<div style={{ height: '50vh' }} />
</Form.Header>
<Form.Item name='name2' label='姓名' rules={[{ required: true }]}>
<Input
placeholder='请输入姓名'
onFocus={e => {
target.current = e?.target;
}}
onBlur={() => {
target.current = null;
}}
/>
</Form.Item>
<Form.Item name='address2' label='地址' help='详情地址'>
<Input
placeholder='请输入地址'
onFocus={e => {
target.current = e?.target;
}}
onBlur={() => {
target.current = null;
}}
/>
</Form.Item>
</Form>
<div style={{ height: '50vh' }} />
</div>
);
};
export default TestComp;