前言:前端時間也是應項目的需求開始了h5移動端的折騰之旅,在目前中臺的基礎上擴展了兩個ToC移動端項目,下面就是在h5移動端表單頁面鍵盤彈出收起兼容性的一些總結。
問題
在 h5 項目中,我們會經常遇到一些表單頁面,在輸入框獲取焦點時,會自動觸發鍵盤彈起,而鍵盤彈出在 IOS 與 Android 的 webview 中表現并非一致,同時當我們主動觸發鍵盤收起時也同樣存在差異化。
鍵盤彈出
鍵盤收起
期望的結果
針對不同系統觸發鍵盤彈出收起時的差異化,我們希望功能流暢的同時,盡量保持用戶體驗的一致性。
對癥下藥
上面我們理清了目前市面上兩大主要系統的差異性,接下來就需對癥下藥了。
在 h5 中目前沒有接口可以直接監聽鍵盤事件,但我們可以通過分析鍵盤彈出、收起的觸發過程及表現形式,來判斷鍵盤是彈出還是收起的狀態。
系統判斷
在實踐中我們可以通過 userAgent 來判斷目前的系統:
const ua = window.navigator.userAgent.toLocaleLowerCase();const isIOS = /iphone|ipad|ipod/.test(ua);const isAndroid = /android/.test(ua);
IOS 處理
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);
Android 處理
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 封裝
在 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;
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答