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

文章起因

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

src/core/util/env.js

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.js

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開始支持;

相關文檔

selectionchange

DocumentOrShadowRoot.activeElement

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章