1. 安卓和IOS兼容方法:
export const monitorSoftKeyboard = callback => {
// 1. Android系统
const originalHeight = document.documentElement.clientHeight || document.body.clientHeight;
window.addEventListener('resize', () => {
//键盘弹起与隐藏都会引起窗口的高度发生变化
const resizeHeight = document.documentElement.clientHeight || document.body.clientHeight;
if (resizeHeight - 0 < originalHeight - 0) {
//当软键盘弹起,在此处操作
callback(true);
} else {
//当软键盘收起,在此处操作
callback(false);
}
});
// 2. IOS系统(兼容)
document.body.addEventListener('focusin', () => {
//软键盘弹出的事件处理
callback(true);
});
document.body.addEventListener('focusout', () => {
//软键盘收起的事件处理
callback(false);
});
};
// page
// 控制整个按钮底部的显示与隐藏
const [hideBottom, setHideBottom] = useState(false);
useEffect(() => {
monitorSoftKeyboard(isUp => {
if (isUp) {
setHideBottom(true);
} else {
setHideBottom(false);
}
});
}, []);
2. Android端
// 控制整个按钮底部的显示与隐藏
const [hideBottom, setHideBottom] = useState(false);
useEffect(() => {
// 原窗口高度
const originalHeight = document.documentElement.clientHeight || document.body.clientHeight;
window.addEventListener('resize', () => {
//键盘弹起与隐藏都会引起窗口的高度发生变化
const resizeHeight = document.documentElement.clientHeight || document.body.clientHeight;
if (resizeHeight - 0 < originalHeight - 0) {
//当软键盘弹起,在此处操作
setHideBottom(true);
} else {
//当软键盘收起,在此处操作
setHideBottom(false);
}
});
}, []);
或者
const [hideBottom, setHideBottom] = useState(false);
useEffect(() => {
// 原窗口高度
const originalHeight = document.documentElement.clientHeight || document.body.clientHeight;
window.onresize = () => {
//键盘弹起与隐藏都会引起窗口的高度发生变化
const resizeHeight = document.documentElement.clientHeight || document.body.clientHeight;
if (resizeHeight - 0 < originalHeight - 0) {
//当软键盘弹起,在此处操作
setHideBottom(true);
} else {
//当软键盘收起,在此处操作
setHideBottom(false);
}
};
}, []);
3. IOS端
// 控制整个按钮底部的显示与隐藏
const [hideBottom, setHideBottom] = useState(false);
useEffect(() => {
document.body.addEventListener('focusin', () => {
//软键盘弹出的事件处理
setHideBottom(true);
});
document.body.addEventListener('focusout', () => {
//软键盘收起的事件处理
setHideBottom(false);
});
}, []);
原文链接:https://blog.csdn.net/yiguoxiaohai/article/details/125872156
小程序(React)H5移动端如何监听软键盘弹起、收起
最新推荐文章于 2024-04-16 16:33:11 发布