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()
    },

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM