本文首發於 hzzly的博客原文連接:h5手機鍵盤彈出收起的處理前端
前言:前端時間也是應項目的需求開始了h5移動端的折騰之旅,在目前中臺的基礎上擴展了兩個ToC移動端項目,下面就是在h5移動端表單頁面鍵盤彈出收起兼容性的一些總結。
在 h5 項目中,咱們會常常遇到一些表單頁面,在輸入框獲取焦點時,會自動觸發鍵盤彈起,而鍵盤彈出在 IOS 與 Android 的 webview 中表現並不是一致,同時當咱們主動觸發鍵盤收起時也一樣存在差別化。react
針對不一樣系統觸發鍵盤彈出收起時的差別化,咱們但願功能流暢的同時,儘可能保持用戶體驗的一致性。android
上面咱們理清了目前市面上兩大主要系統的差別性,接下來就需對症下藥了。ios
在 h5 中目前沒有接口能夠直接監聽鍵盤事件,但咱們能夠經過分析鍵盤彈出、收起的觸發過程及表現形式,來判斷鍵盤是彈出仍是收起的狀態。web
鍵盤收起:當觸發其餘頁面區域收起鍵盤時,咱們能夠監聽 focusout 事件,在裏面實現鍵盤收起後所需的頁面邏輯。而在經過鍵盤按鈕收起鍵盤時在 ios 與 android 端存在差別化表現,下面具體分析:app
在實踐中咱們能夠經過 userAgent 來判斷目前的系統:iphone
const ua = window.navigator.userAgent.toLocaleLowerCase(); const isIOS = /iphone|ipad|ipod/.test(ua); const isAndroid = /android/.test(ua);
let isReset = true; //是否歸位 this.focusinHandler = () => { isReset = false; //聚焦時鍵盤彈出,焦點在輸入框之間切換時,會先觸發上一個輸入框的失焦事件,再觸發下一個輸入框的聚焦事件 }; this.focusoutHandler = () => { isReset = true; setTimeout(() => { //當焦點在彈出層的輸入框之間切換時先不歸位 if (isReset) { window.scroll(0, 0); //肯定延時後沒有聚焦下一元素,是由收起鍵盤引發的失焦,則強制讓頁面歸位 } }, 30); }; document.body.addEventListener('focusin', this.focusinHandler); document.body.addEventListener('focusout', this.focusoutHandler);
const originHeight = document.documentElement.clientHeight || document.body.clientHeight; this.resizeHandler = () => { const resizeHeight = document.documentElement.clientHeight || document.body.clientHeight; const activeElement = document.activeElement; if (resizeHeight < originHeight) { // 鍵盤彈起後邏輯 if (activeElement && (activeElement.tagName === "INPUT" || activeElement.tagName === "TEXTAREA")) { setTimeout(()=>{ activeElement.scrollIntoView({ block: 'center' });//焦點元素滾到可視區域的問題 },0) } } else { // 鍵盤收起後邏輯 } }; window.addEventListener('resize', this.resizeHandler);
在 react 中咱們能夠寫一個類裝飾器來修飾表單組件。函數
類裝飾器:類裝飾器在類聲明以前被聲明(緊靠着類聲明)。 類裝飾器應用於類構造函數,能夠用來監視,修改或替換類定義。
// keyboard.tsx /* * @Description: 鍵盤處理裝飾器 * @Author: hzzly * @LastEditors: hzzly * @Date: 2020-01-09 09:36:40 * @LastEditTime: 2020-01-10 12:08:47 */ import React, { Component } from 'react'; const keyboard = () => (WrappedComponent: any) => class HOC extends Component { focusinHandler: (() => void) | undefined; focusoutHandler: (() => void) | undefined; resizeHandler: (() => void) | undefined; componentDidMount() { const ua = window.navigator.userAgent.toLocaleLowerCase(); const isIOS = /iphone|ipad|ipod/.test(ua); const isAndroid = /android/.test(ua); if (isIOS) { // 上面 IOS 處理 ... } if (isAndroid) { // 上面 Android 處理 ... } } componentWillUnmount() { if (this.focusinHandler && this.focusoutHandler) { document.body.removeEventListener('focusin', this.focusinHandler); document.body.removeEventListener('focusout', this.focusoutHandler); } if (this.resizeHandler) { document.body.removeEventListener('resize', this.resizeHandler); } } render() { return <WrappedComponent {...this.props} />; } }; export default keyboard;
// PersonForm.tsx @keyboard() class PersonForm extends PureComponent<{}, {}> { // 業務邏輯 ... } export default PersonForm;