web端实现复制指定内容

2020-12-03  本文已影响0人  mn_li

使用已有插件

  1. 插件github:https://github.com/zenorocha/clipboard.js
  2. 使用方式

使用textarea

// 创建文本域元素
const tempTextarea = document.createElement('textarea');
tempTextarea.value = "复制内容";
document.body.appendChild(tempTextarea);
// 设置文本域被选中
tempTextarea.select();
// 执行选中动作
document.execCommand('copy');

复制当前页面已有内容

选中参考:https://www.cnblogs.com/sanqianjin/p/9259033.html

// 获取要选中的元素,创建选中区域
const range = document.createRange();
const referenceNode = document.querySelector('.links-wrap'); 
const selection = window.getSelection();
// 设置选中
range.selectNodeContents(referenceNode);
selection.removeAllRanges();
selection.addRange(range)
// 执行复制
const result = document.execCommand('copy');
// 取消选中
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
上一篇 下一篇

猜你喜欢

热点阅读