在前端开发中,使用 JavaScript 实现选中并复制内容的功能,可以通过以下步骤完成:
可以使用现代浏览器提供的 Clipboard API 来实现复制功能。以下是一个示例代码:
<!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="Hello, World!" id="textToCopy">
<button onclick="copyText()">Copy Text</button>
<script>
function copyText() {
const textInput = document.getElementById('textToCopy');
// 选中文本
textInput.select();
textInput.setSelectionRange(0, 99999); // 对于移动设备
// 复制到剪贴板
document.execCommand('copy');
alert('Text copied to clipboard!');
}
</script>
</body>
</html>
document.execCommand('copy')
方法在大多数现代浏览器中有效,但在某些旧版本浏览器中可能不支持。async function copyTextUsingClipboardAPI() {
const textInput = document.getElementById('textToCopy');
try {
await navigator.clipboard.writeText(textInput.value);
alert('Text copied to clipboard!');
} catch (err) {
console.error('Failed to copy text: ', err);
// 备选方案:使用 execCommand
textInput.select();
textInput.setSelectionRange(0, 99999);
document.execCommand('copy');
alert('Text copied to clipboard!');
}
}
通过上述方法,可以在前端实现选中并复制内容的功能。根据具体需求和浏览器兼容性,可以选择合适的方法来实现这一功能。
领取专属 10元无门槛券
手把手带您无忧上云