在前端开发中,实现按钮复制到剪切板的功能,通常会用到现代浏览器提供的 Clipboard API。以下是相关的基础概念、优势、类型、应用场景以及实现方式:
Clipboard API 提供了一种访问剪切板的接口,允许网页读取和写入剪切板内容。主要的方法包括 navigator.clipboard.writeText()
和 navigator.clipboard.readText()
。
navigator.clipboard.writeText(text)
navigator.clipboard.readText()
以下是一个简单的示例代码,展示如何实现点击按钮复制文本到剪切板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Copy to Clipboard Example</title>
</head>
<body>
<input type="text" value="https://example.com" id="textToCopy" readonly>
<button id="copyButton">Copy Link</button>
<script>
document.getElementById('copyButton').addEventListener('click', async () => {
const text = document.getElementById('textToCopy').value;
try {
await navigator.clipboard.writeText(text);
alert('Link copied to clipboard!');
} catch (err) {
console.error('Failed to copy text: ', err);
alert('Failed to copy link. Please try again.');
}
});
</script>
</body>
</html>
navigator.clipboard
是否存在来提供降级方案,例如使用 document.execCommand('copy')
。function fallbackCopyTextToClipboard(text) {
const textArea = document.createElement("textarea");
textArea.value = text;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
const successful = document.execCommand('copy');
const msg = successful ? 'successful' : 'unsuccessful';
console.log('Fallback: Copying text command was ' + msg);
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
}
document.body.removeChild(textArea);
}
document.getElementById('copyButton').addEventListener('click', () => {
const text = document.getElementById('textToCopy').value;
if (!navigator.clipboard) {
fallbackCopyTextToClipboard(text);
return;
}
navigator.clipboard.writeText(text).then(() => {
alert('Link copied to clipboard!');
}).catch(err => {
console.error('Failed to copy text: ', err);
alert('Failed to copy link. Please try again.');
});
});
通过以上方法,可以实现一个兼容性较好的按钮复制剪切板功能。
领取专属 10元无门槛券
手把手带您无忧上云