js复制指定内容到粘贴板(兼容ie、火狐、谷歌)

417 阅读1分钟
export default {
	data() {
      name:'自定义粘贴板'
    },
    mounted() {
      this.documentOnkey()
    },
    methods: {
        documentOnkey() {
            let that = this
            document.oncopy = () => {
              let list =[0,2,3,4,5,56,78]
              if (that.statusObj.choice === 'alone' && list && list.length > 0) {
                that.copyTxt(list)
              }
            }
            document.onpaste = e => {
              var pastedText = undefined
              // IE
              if (window.clipboardData && window.clipboardData.getData) {
                pastedText = window.clipboardData.getData('Text')
              } else {
                pastedText = e.clipboardData.getData('text/plain') //e.clipboardData.getData('text/plain');
              }
              let list = JSON.parse(pastedText)
              if (list && list.length > 0) {
                that.pasteTxt(list)
                return false
              }
            }
        },
        // 复制图形
        copyTxt(list) {// 假设需要粘贴的内容是数组类型
          let text = JSON.stringify(list)
          if (typeof document.execCommand !== 'function') {
            return
          }
          let dom = document.createElement('textarea')
          dom.value = text
          dom.setAttribute('style', 'display: block;width: 1px;height: 1px;')
          document.body.appendChild(dom)
          dom.select()
          let result = document.execCommand('copy')
          document.body.removeChild(dom)
          if (result) {
            return
          }
          if (typeof document.createRange !== 'function') {
            return
          }
          let range = document.createRange()
          let div = document.createElement('div')
          div.innerHTML = text
          div.setAttribute('style', 'height: 1px;fontSize: 1px;overflow: hidden;')
          document.body.appendChild(div)
          range.selectNode(div)
          const selection = window.getSelection()
          if (selection.rangeCount > 0) {
            selection.removeAllRanges()
          }
          selection.addRange(range)
          document.execCommand('copy')
        },
        // 粘贴图形
        pasteTxt(list) {
          // 对粘贴板的内容进行自定义操作
          console.log(list)
        }
    }
}