keyboard.js 1.8 KB
Newer Older
1 2 3 4
import {
  plusReady
} from 'uni-shared'

5 6 7
function hideKeyboard () {
  document.activeElement.blur()
}
8 9 10 11
/**
 * 保证iOS点击输入框外隐藏键盘
 */
function iosHideKeyboard () { }
12 13 14

export default {
  name: 'Keyboard',
15 16
  props: {
    cursorSpacing: {
Q
qiang 已提交
17
      type: [Number, String],
18 19 20 21 22 23 24
      default: 0
    },
    adjustPosition: {
      type: Boolean,
      default: true
    }
  },
25 26 27 28 29 30 31 32 33 34 35 36
  watch: {
    focus (val) {
      if (val) {
        this.showSoftKeybord()
      }
    }
  },
  mounted () {
    if (this.autoFocus || this.focus) {
      this.showSoftKeybord()
    }
  },
37
  beforeDestroy () {
38
    this.onKeyboardHide()
39 40 41 42 43
  },
  methods: {
    initKeyboard (el) {
      el.addEventListener('focus', () => {
        UniViewJSBridge.subscribe('hideKeyboard', hideKeyboard)
44
        document.addEventListener('click', iosHideKeyboard, false)
45
        this.setSoftinputTemporary()
46
      })
47
      el.addEventListener('blur', this.onKeyboardHide)
48 49
    },
    showSoftKeybord () {
50
      plusReady(() => {
51 52 53 54
        plus.key.showSoftKeybord()
      })
    },
    setSoftinputTemporary () {
55
      plusReady(() => {
56 57 58 59 60 61 62 63 64 65
        var currentWebview = plus.webview.currentWebview()
        var style = currentWebview.getStyle() || {}
        if (style.softinputMode === 'adjustResize') {
          return
        }
        var rect = this.$el.getBoundingClientRect()
        currentWebview.setSoftinputTemporary && currentWebview.setSoftinputTemporary({
          mode: this.adjustPosition ? 'adjustPan' : 'nothing',
          position: {
            top: rect.top,
Q
qiang 已提交
66
            height: rect.height + (Number(this.cursorSpacing) || 0)
67 68 69
          }
        })
      })
70 71 72 73
    },
    onKeyboardHide () {
      UniViewJSBridge.unsubscribe('hideKeyboard', hideKeyboard)
      document.removeEventListener('click', iosHideKeyboard, false)
74 75 76
    }
  }
}