微信浏览器,ios软键盘收回,上推页面无法恢复原位置

43 阅读1分钟

问题描述:

使用webview打开的h5页面,在微信打开,ios软键盘弹起,页面会被推上去,收起键盘,页面不会恢复到原位置。

不用考虑针对ios做,键盘弹起页面不被推起的处理;因为这是ios的系统行为,h5上是实现不了的。

ios键盘弹起是对webview整体进行平移处理;安卓上键盘弹起,页面不会滚动,是因为安卓会压缩webview容器的高度。

可以在ios和安卓获取window.innerHeight值,当键盘弹起,ios值不变,但是安卓值会变小;

解决方案:

在触发焦点时,记录页面的scrollTop,失去焦点,将页面滚动到原位置

<input onBlur={handleBlur} onFocus={handleFocus}/>

const scrollTimerRef = useRef<any>(null);
const scrollHeightRef = useRef<number>(0);

const handleFocus = () => {
 scrollHeightRef.current = document.documentElement.scrollTop || document.body.scrollTop || 0;
}

/**
* 解决在微信上,ios键盘收回,被上推的页面未恢复到原位置问题
* 失去焦点,键盘收起,延迟一下,否则点击发布按钮,先执行滚动,不会执行click事件
*/
  const handleBlur = () => {
    if (isWeixin && os === 'ios') {
      if (scrollTimerRef.current) {
        clearTimeout(scrollTimerRef.current);
      }
      scrollTimerRef.current = setTimeout(() => {
        window.scrollTo(0, scrollHeightRef.current);
        scrollTimerRef.current = null;
      }, 100);
    }
  };