VUE3的学习和使用(三)用execCommand实现文本复制


利用execCommand复制文本



// 复制监测详情内容
const copyText = () => {
  // 获取需要复制的元素以及元素内的文本内容
  const container = document.getElementById('copy-text');
  const text = container.innerText;
  // 添加一个input元素放置需要的文本内容
  const copyContent= document.createElement('input');
  copyContent.value = text;
  document.body.appendChild(copyContent);
  // 选中并复制文本到剪切板
  copyContent.select();
  document.execCommand('copy');
  // 移除input元素
  document.body.removeChild(copyContent);
  console.log('复制成功');
};