1. 程式人生 > 其它 >js實現攔截貼上並修改貼上內容

js實現攔截貼上並修改貼上內容

遇到這樣一個需求: 複製了excel表格的資料,然後貼上的時候需要把表格裡面的資料全部都用','分隔.
解決思路: 監聽貼上事件,讀取貼上的內容,把貼上的內容裡面的換行和tab都替換成',',然後獲取當前聚焦的元素,修改當前聚焦元素的value.

    // 增加貼上監聽
    addPasteListener() {
      document.addEventListener('paste', this.beforPasteHandler)
    },
    // 貼上時把tab和換行替換成逗號
    beforPasteHandler(event) {
      let paste = (event.clipboardData || window.clipboardData).getData('text')
      paste = paste.replace(/(\r|\n|\t)/g, ',')
      paste = paste.replace(/(,,)/g, ',')
      if (paste.charAt(paste.length - 1) === ',') {
        paste = paste.substr(0, paste.length - 1)
      }
      const selection = document.activeElement // 獲取當前焦點所在元素
      if (!selection || selection.tagName.toUpperCase() === 'BODY') return false
      selection.value = paste
      event.preventDefault()
    },
    // 移除離開頁面提示
    removePasteListener() {
      window.removeEventListener('beforeunload', this.beforPasteHandler)
    }