剪切和粘贴文本是应用程序(尤其是桌面应用程序)最常用的功能之一。如何在 Web 上复制文本?方法有新旧两种。这取决于所使用的浏览器。
新方法
使用 Async Clipboard API
The Clipboard.writeText()
方法接受一个字符串并返回一个 Promise,当文本成功写入剪贴板时,该 Promise 将会被解析。 Clipboard.writeText()
只能从具有焦点的 window
对象中使用。
经典方法
使用 document.execCommand()
调用 document.execCommand('copy')
返回一个布尔值,指示复制是否成功。在用户手势(例如 点击处理程序)中调用此命令。与 Async Clipboard API 相比,此方法存在局限性。execCommand()
方法仅适用于 DOM 元素。由于它是同步的,因此复制大量数据(尤其是在必须以某种方式转换或清理数据的情况下)可能会阻止页面。
渐进增强
const copyButton = document.querySelector('#copyButton');
const out = document.querySelector('#out');
if ('clipboard' in navigator) {
copyButton.addEventListener('click', () => {
navigator.clipboard.writeText(out.value)
.then(() => {
console.log('Text copied');
})
.catch((err) => console.error(err.name, err.message));
});
} else {
copyButton.addEventListener('click', () => {
const textArea = document.createElement('textarea');
textArea.value = out.value;
textArea.style.opacity = 0;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
const success = document.execCommand('copy');
console.log(`Text copy was ${success ? 'successful' : 'unsuccessful'}.`);
} catch (err) {
console.error(err.name, err.message);
}
document.body.removeChild(textArea);
});
}
延伸阅读
演示
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
rel="icon"
href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🎉</text></svg>"
/>
<title>How to copy text</title>
</head>
<body>
<h1>How to copy text</h1>
<textarea rows="3">
Some sample text for you to copy. Feel free to edit this.</textarea
>
<button type="button">Copy</button>
</body>
</html>
CSS
:root {
color-scheme: dark light;
}
html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
margin: 1rem;
font-family: system-ui, sans-serif;
}
button {
display: block;
}
JS
const textarea = document.querySelector('textarea');
const button = document.querySelector('button');
button.addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(textarea.value);
} catch (err) {
console.error(err.name, err.message);
}
});