复制到剪切板 clipboard

 方法一:#

复制代码
function copyHandle(content){
  let copy = (e)=>{
      e.preventDefault()
      e.clipboardData.setData('text/plain',content)
      alert('复制成功')
      document.removeEventListener('copy',copy)
  }
  document.addEventListener('copy',copy)
  document.execCommand("Copy");
}
复制代码

过程:
1. document.execCommand("Copy")  触发复制监听事件
2. e.clipboardData.setData 将内容添加到剪切板
3. 复制完成后,取消监听事件,否则会触发多次
应用场景:
已知复制的内容,传入内容直接调用函数

方法二:#

复制代码
function copyLink(dom) {
      let range = document.createRange();
      let selection = window.getSelection();
      range.selectNode(dom);
      selection.removeAllRanges();
      selection.addRange(range);
      let bool = document.execCommand("copy", "false", null);
      if (bool) {
        alert("复制成功");
      }
      document.execCommand("unselect", "false", null);
}
复制代码

过程:

1. range.selectNode 创建选取内容范围

2. removeAllRanges 清除已选择的内容

3. addRanges 添加选取内容,模拟用户选取

4. document.execCommand("Copy") 触发复制事件

5. document.execCommand("unselect", "false", null) 取消选取区域



other

<button class="copyButton" style="display: none" @click="e => copy(e, index)">copy</button>

/**
* 右键菜单 复制
*/
public handleMenuCopy() {
const a = document.getElementsByClassName('copyButton');
/* eslint-disable */
// @ts-ignore
a[this.copyIndex]?.click();
}




public copy(e: any, index: number) {
const clipboard = new Clipboard(e.target, { text: () => this.getCopyText(index) });
clipboard.on('success', e => {
this.$message({ type: 'success', message: '复制成功' });
clipboard.destroy();
});

clipboard.on('error', function(e) {
clipboard.destroy();
});
/* eslint-disable */
// @ts-ignore
clipboard.onClick(e);
}

public getCopyText(index: number) {
const payload =
this.newChatList[index]?.type === EventMessageType.TEXT
? this.newChatList[index]?.payload
: this.newChatList[index]?.payload?.message?.payload;
return this.selectText !== '' ? this.selectText : ImgService.resolveTitle(payload);
}



posted @ 2021-01-15 15:27  _ryze  阅读(360)  评论(0编辑  收藏  举报