一、前言:
开发中遇到一个问题,输入框唤起键盘后,输入框会被键盘遮挡,需要手动滑动才能漏出来,影响用户体验
二、解决办法:
1.ios和android手机唤起的windows事件不一样,要分别处理
2.document.body.scrollTop无效,可以用document.documentElement.scrollTop替换
三、具体实现过程:
// 判断手机 - ios/andriod
function isIOS() {
const u = navigator.userAgent;
return !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
}
/**
* @description: 键盘弹起,输入框被遮挡
*/
function cInput() {
if (isIOS()) {
window.addEventListener('focusin', function () {
console.log(1+document.activeElement.tagName);
if (
document.activeElement.tagName === 'INPUT' ||
document.activeElement.tagName === 'TEXTAREA'
) {
setTimeout(function () {
document.documentElement.scrollTop = document.body.scrollHeight;
}, 0);
}
});
} else {
window.addEventListener('resize', function () {
console.log(2+ document.activeElement.tagName);
if (
document.activeElement.tagName === 'INPUT' ||
document.activeElement.tagName === 'TEXTAREA'
) {
setTimeout(function () {
document.activeElement.scrollIntoView();
}, 0);
}
});
}
}
export {
isIOS,
cInput
}
用的时候直接调用cInput()就行
本文介绍了一个在开发中常见的问题,即输入框被键盘遮挡,提供了针对iOS和Android系统的不同解决方案,通过判断设备类型并使用相应事件处理,确保输入框在键盘弹起时自动调整位置,提升用户体验。
4154

被折叠的 条评论
为什么被折叠?



