# 前端js代码片段

# 1. copy文本到剪切板

# document.execCommand

document.execCommand 是一个已经废弃的api,不建议使用

function copyToClipboard(text) {
  const textArea = document.createElement('textarea');
  textArea.value = text;
  textArea.style.position = 'fixed'; // Prevent scrolling to bottom of page in MS Edge
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();
  try {
    document.execCommand('copy');
    document.body.removeChild(textarea);
    console.log('Text copied to clipboard'); // 复制成功
  } catch (err) {
    console.error('Unable to copy text: ', err);
  }
  document.body.removeChild(textArea);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function copyToClipboard(text) {
  if (navigator.clipboard) {
    try {
      navigator.clipboard.writeText(text).then(() => {
        console.log('Text copied to clipboard'); // 复制成功
      });
    } catch (err) {
      console.error('Unable to copy text: ', err); // 复制失败
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11

复制粘贴富文本、表格、图片等

Last Updated: 7/3/2025, 9:57:44 PM