mobile-more
Version:
基于 antd-mobile v5 扩展移动端 UI 组件
37 lines (35 loc) • 1.28 kB
JavaScript
import { useEffect } from 'react';
import { delay, isBrowser } from 'ut2';
import { getClientHeight } from "../utils/dom";
var inputTagNames = ['INPUT', 'TEXTAREA'];
// 调整输入元素滚动
var adjustInputElementScrollIntoView = function adjustInputElementScrollIntoView() {
var activeElement = document.activeElement;
if (activeElement && inputTagNames.includes(activeElement.tagName)) {
delay(function () {
var rect = activeElement.getBoundingClientRect();
var winHeight = getClientHeight(window);
if (rect.top < 0) {
// 顶部超出屏幕,滚动至顶部
activeElement.scrollIntoView();
} else if (rect.top > winHeight / 2) {
// 中下区域,滚动至中间
activeElement.scrollIntoView({
block: 'center'
});
}
}, 0);
}
};
// 当 android 输入框获取焦点时,整个视窗大小会调整,导致输入框元素移除视窗外
function useResizeInputScrollIntoView() {
useEffect(function () {
if (isBrowser) {
window.addEventListener('resize', adjustInputElementScrollIntoView);
return function () {
window.removeEventListener('resize', adjustInputElementScrollIntoView);
};
}
}, []);
}
export default useResizeInputScrollIntoView;