在构建网站时,一个非常普遍的需求是能够通过单击按钮将文本复制到剪贴板。在现代浏览器中,使用navigator.clipboard
API 访问系统剪切板,利用clipboard.writeText
复制到剪贴板,再通过clipboard.readText
获取剪贴板内容即可实现。
实现效果
源码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.copy {
width: 300px;
height: 100px;
border: 1px solid saddlebrown;
}
</style>
</head>
<body>
<p>这是待复制的内容:如何将文本复制到剪贴板</p>
<button id="once">一键复制</button>
<button id="content">展示剪贴板内容</button>
<p class="copy"></p>
<script>
const copyToClipboard = (str) => {
if (navigator?.clipboard?.writeText) {
return navigator?.clipboard?.writeText(str);
}
return Promise.reject();
};
const getCopyClipboard = () => {
return navigator.clipboard.readText();
};
const btn = document.querySelector("#content");
const p = document.querySelector(".copy");
const once = document.querySelector('#once');
once.addEventListener('click', (str) => {
const p = document.querySelector('p');
copyToClipboard(p.innerText).then(() => {
alert('复制成功');
})
});
btn.addEventListener("click", async () => {
const copyContent = await getCopyClipboard();
p.innerHTML = copyContent;
});
</script>
</body>
</html>
参考资料
- Navigator:clipboard 属性