hookehuyr

✨ feat: 新增监听弹出框功能

1 +/*
2 + * @Date: 2022-06-20 01:22:50
3 + * @LastEditors: hookehuyr hookehuyr@gmail.com
4 + * @LastEditTime: 2022-06-20 01:23:18
5 + * @FilePath: /tswj/src/composables/useMonitorKeyboard.js
6 + * @Description: 文件描述
7 + */
8 +/**
9 + * @class 监听虚拟键盘
10 + * @classdesc 监听虚拟键盘弹出隐藏
11 + * @public onEnd 结束监听虚拟键盘
12 + * @public onShow 传递一个回调 监听虚拟键盘弹出
13 + * @public onHidden 传递一个回调 监听虚拟键盘隐藏
14 + */
15 +class MonitorKeyboard {
16 + constructor() {
17 + this.type = this.IsIA();
18 + this.originalHeight = window.innerHeight;
19 + }
20 +
21 + /**
22 + * @function IsIA 获取设备类型
23 + * @param 1 Android 2 iOS
24 + */
25 + IsIA = () => {
26 + const userAgent = typeof window === 'object' ? window.navigator.userAgent : '';
27 + if (/android/i.test(userAgent)) {
28 + return 1;
29 + } else if (/iPhone|iPod|iPad/i.test(userAgent)) {
30 + return 2;
31 + }
32 + }
33 +
34 + // Android系统
35 + onResize = () => {
36 + //键盘弹起与隐藏都会引起窗口的高度发生变化
37 + const resizeHeight = window.innerHeight;
38 +
39 + if (this.originalHeight - resizeHeight > 50) {
40 + this.show('Android系统: 软键盘弹出');
41 + } else {
42 + this.hidden('Android系统: 软键盘收起');
43 + }
44 + }
45 +
46 + // iOS获取焦点
47 + onFocusin = () => {
48 + this.show('iOS系统:软键盘弹出');
49 + }
50 +
51 + // iOS失去焦点
52 + onFocusout = () => {
53 + this.hidden('iOS系统:软键盘收起');
54 + }
55 +
56 + /**
57 + * @function onStart 开始监听虚拟键盘
58 + */
59 + onStart = () => {
60 + if (this.type == 1) {
61 + // 获取窗口的高度
62 + window.addEventListener('resize', this.onResize);
63 + }
64 + if (this.type == 2) {
65 + // iOS系统
66 + window.addEventListener('focusin', this.onFocusin);
67 + window.addEventListener('focusout', this.onFocusout);
68 + }
69 + }
70 +
71 + /**
72 + * @function onEnd 结束监听虚拟键盘
73 + */
74 + onEnd = () => {
75 + if (this.type == 1) {
76 + //获取窗口的高度
77 + window.removeEventListener('resize', this.onResize);
78 + }
79 + if (this.type == 2) {
80 + window.removeEventListener('focusin', this.onFocusin);
81 + window.removeEventListener('focusout', this.onFocusout);
82 + }
83 + }
84 +
85 + /**
86 + * @function onShow 传递一个回调函数
87 + * @param 虚拟键盘弹出时触发
88 + */
89 + onShow = (fn) => {
90 + this.show = fn;
91 + }
92 +
93 + /**
94 + * @function onHidden 传递一个回调函数
95 + * @param 虚拟键盘隐藏时触发
96 + */
97 + onHidden = (fn) => {
98 + this.hidden = fn;
99 + }
100 +}
101 +
102 +export default MonitorKeyboard