JavaScript实现点击复制功能。
原理:原生JavaScript提供了一个方法:
window.document.execCommand('copy');
这个方法就是对当前的以选中的字符进行复制,这边就又有一个问题,就是我们该怎么选中?input、textarea等标签提供了select方法,我们就可以使用这个来模拟我们用户选中。我们可以创建一个input标签,当然这个标签要是透明的,或者是不可见的,不能平白无辜在页面上多一个标签吧,然后给这标签的value值赋上我们想要复制的内容,最后我们在执行上面的select模拟选中,最后在执行execCommand(‘copy’)然后再将标签去除就可以啦。
原理很简单,这边直接上代码。
function copy(data, callback) {
//创建input
const input = window.document.createElement('input');
//赋值并设置不可见
input.setAttribute('value', data);
input.setAttribute('display', 'none');
document.body.appendChild(input);
input.select();
let err = undefined;
//捕获异常,如果浏览器不支持则抛出异常。
try {
const status = window.document.execCommand('copy');
if (status) {
callback(err, data);
return;
}
callback(new Error('复制失败'), data);
} catch (error) {
err = error;
callback(err, data);
} finally {
window.document.body.removeChild(input);
}
}
案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="COPY()">复制</button>
</body>
</html>
<script src="./copyText.js"></script>
<script>
function COPY() {
copy('777', (err, data) => {
if (!err) {
console.log(data);
} else {
console.log(err.message);
}
})
}
</script>