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

利用execCommand复制文本

<template>
<button  @click="copyText">复制</button>

<section id="copy-text">
    ...
</section>
</template>

// 复制监测详情内容
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('复制成功');
};
posted on 2022-03-21 10:52  blue_hl  阅读(451)  评论(0编辑  收藏  举报