点击复制
使用 execCommand('copy')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="copy" onclick="copyHandle('copy text')">copy</button>
<script type="text/javascript">
function copyHandle(text) {
// 获取按钮
let copyText = document.getElementById("copy");
// 创建 textarea 元素
let textarea = document.createElement("textarea");
// 设置 value
textarea.value = text;
// 隐藏 textarea
textarea.style.position = "fixed";
textarea.style.top = 0;
textarea.style.left = '-100%';
// 添加到 body
document.body.appendChild(textarea);
// 选中
textarea.select();
// 执行复制
document.execCommand("copy");
// 去除 textarea
document.body.removeChild(textarea);
}
</script>
</body>
</html>
document.execCommand - Web API 接口参考 | MDN (mozilla.org)
优点:适配广
缺点:
调用方式繁琐
此功能已过时。 尽管它在某些浏览器中可能仍然有效,但不鼓励使用它,因为它可能随时被删除。 尽量避免使用它。
使用 Clipboard API
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="copy" onclick="copyHandle(683)">copy</button>
<script type="text/javascript">
async function copyHandle(text) {
// 执行
await navigator.clipboard.writeText(text)
}
</script>
</body>
</html>
Clipboard API - Web API 接口参考 | MDN (mozilla.org)
优点:调用方便
缺点:适配范围较窄