教你如何解決IE9的輸入框input事件沒法監聽右鍵菜單的剪切、撤銷、刪除對內容的改變的問題

文章原由

看Vue源代碼內置指令時,發現了Vue對於IE9的selectionchange事件作了特殊處理,這引發了個人興趣。原來Vue對全局的selectionchange事件進行監聽,一旦發現就會嘗試觸發document.activeElement當前文檔激活對象的input事件。
具體代碼以下:javascript

src/core/util/env.jsjava

export const inBrowser = typeof window !== 'undefined'
export const UA = inBrowser && window.navigator.userAgent.toLowerCase()
export const isIE = UA && /msie|trident/.test(UA)
export const isIE9 = UA && UA.indexOf('msie 9.0') > 0

src/platforms/web/runtime/directives/model.jsweb

if (isIE9) {
  document.addEventListener('selectionchange', () => {
    const el = document.activeElement
    if (el && el.vmodel) {
      trigger(el, 'input')
    }
  })
}
function trigger (el, type) {
  const e = document.createEvent('HTMLEvents')
  e.initEvent(type, true, true)
  el.dispatchEvent(e)
}

爲何要這樣兼容

原來IE9輸入框input事件沒法監聽到鍵盤的backspace鍵和delete鍵對內容的改變,以及右鍵菜單的剪切、撤銷、刪除對內容的改變,用keyup事件咱們能夠解決鍵盤backspace鍵delete鍵的問題,可是對於右鍵對於文本的操做仍是無能爲力,還好有selectionchange事件,它能夠在文檔上的當前文本選擇被改變時觸發,例如文本選擇、剪切、刪除、粘貼等操做。瀏覽器

selectionchange事件須要注意的點

  • selectionchange事件只能綁定在Document接口對象上,其餘元素綁定無效,並且不能夠取消、也不能冒泡;
  • 須要注意的是Chrome上右鍵菜單的剪切並不會觸發selectionchange事件;
  • IE瀏覽器從IE9開始支持;

相關文檔

selectionchangeide

DocumentOrShadowRoot.activeElementspa

相關文章
相關標籤/搜索