web复制文字 + 复制即用修改免修改 + 原生代码实现
- 有做新老版本API兼容
- 不需要使用第三方包增加体积
promise
风格
复制即可使用
const copy = async (text = "") => {
if (window._copy_tag_id === undefined) {
window._copy_tag_id = "copy_keys_" + new Date().getTime();
}
try {
await navigator.clipboard.writeText(text);
} catch (err) {
let input = document.getElementById(window._copy_tag_id);
if (input === null) {
input = document.createElement("input");
input.style.display = "none";
input.id = window._copy_tag_id;
document.body.appendChild(input);
}
input.value = text;
input.select();
document.execCommand("copy");
input.value = "";
}
};
测试demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>通用复制实现</title>
</head>
<body>
<button id="test">test</button>
<div id="test"></div>
<script>
const copy = async (text = "") => {
if (window._copy_tag_id === undefined) {
window._copy_tag_id = "copy_keys_" + new Date().getTime();
}
try {
await navigator.clipboard.writeText(text);
} catch (err) {
let input = document.getElementById(window._copy_tag_id);
if (input === null) {
input = document.createElement("input");
input.style.display = "none";
input.id = window._copy_tag_id;
document.body.appendChild(input);
}
input.value = text;
input.select();
document.execCommand("copy");
input.value = "";
}
};
document.getElementById("test").onclick = async () => {
console.log("test");
copy("测试复制");
};
</script>
</body>
</html>