1. 程式人生 > 其它 >vue 監聽 input框focus 後虛擬鍵盤的彈出和收起

vue 監聽 input框focus 後虛擬鍵盤的彈出和收起

1,首先建立一個 virtualkeyboard.js檔案  檔名無所謂

/**
 *
 * @class 監聽虛擬鍵盤
 * @classdesc 監聽虛擬鍵盤彈出隱藏
 *  @public onEnd 結束監聽虛擬鍵盤
 *  @public onShow 傳遞一個回撥 監聽虛擬鍵盤彈出
 *  @public onHidden 傳遞一個回撥 監聽虛擬鍵盤隱藏
 */
class VirtualKeyboard {
  /** @param 裝置型別 1 安卓 2蘋果  */
 

  constructor() {
    this.type = this.IsIA()
    this.originalHeight =
      document.documentElement.clientHeight 
|| document.body.clientHeight } /** * @function onShow 傳遞一個回撥函式 * @param 虛擬鍵盤彈出時觸發 */ onShow = (fn) => { this.show = fn } /** * @function onHidden 傳遞一個回撥函式 * @param 虛擬鍵盤隱藏時觸發 */ onHidden = (fn) => { this.hidden = fn } /** @function onStart 開始監聽虛擬鍵盤
*/ onStart = () => { if (this.type == 1) { //獲取原視窗的高度 window.addEventListener('resize', this.onResize) } if (this.type == 2) { // 蘋果系統 document.body.addEventListener('focusin', this.onFocusin) document.body.addEventListener('focusout', this.onFocusout) } }
/** @function onEnd 結束 監聽 虛擬鍵盤 */ onEnd = () => { if (this.type == 1) { //獲取原視窗的高度 window.removeEventListener('resize', this.onResize) } if (this.type == 2) { document.body.removeEventListener('focusin', this.onFocusin) document.body.removeEventListener('focusout', this.onFocusout) } } IsIA = () => { if (/android/gi.test(navigator.appVersion)) { return 1 //安卓 } else if ( navigator.userAgent.indexOf('iPhone') != -1 || navigator.userAgent.indexOf('iPod') != -1 || navigator.userAgent.indexOf('iPad') != -1 ) { return 2 // 蘋果 } } onResize = () => { //安卓系統 //鍵盤彈起與隱藏都會引起視窗的高度發生變化 let resizeHeight = document.documentElement.clientHeight || document.body.clientHeight if (this.originalHeight - resizeHeight > 50) { //當軟鍵盤彈起,在此處操作 this.show('安卓系統: 當軟鍵盤彈起,在此處操作') } else { //當軟鍵盤收起,在此處操作 this.hidden('安卓系統: 當軟鍵盤彈起,在此處操作') } } // 蘋果獲取焦點 onFocusin = () => { //軟鍵盤彈出的事件處理 this.show('蘋果系統:軟鍵盤彈出的事件處理') } // 蘋果失去焦點 onFocusout = () => { //軟鍵盤收起的事件處理 this.hidden('蘋果系統:軟鍵盤收起的事件處理') } } export default VirtualKeyboard

2,在需要的頁面引入上面建立的js

import VirtualKeyboard from '../plugin/watchKeyBorad'  //這是自己的路徑
//然後在周期函式內引入函式即可我是寫在mounted函式中的
mounted(){
  this.virtualKeyboard = new VirtualKeyboard() //建立物件
  this.virtualKeyboard.onStart()    //開始監聽
//監聽虛擬鍵盤彈出事件
    this.virtualKeyboard.onShow(() => {  
//處理事件  
        console.log('虛擬鍵盤彈出要執行的事件')
     })
//監聽鍵盤收起的事件
   this.virtualKeyboard.onHidden(() => {
          console.log('鍵盤收起事件')
        })


}

3,在離開頁面的時候一定要登出 監聽事件  不然會導致記憶體洩露

  destroyed(){
        // 一般寫在頁面解除安裝或元件解除安裝的生命週期
        this.virtualKeyboard.onEnd()
    },