在网页上点击按钮复制
在 Github 上点击克隆项目时, 点击一个按钮就实现了复制链接到剪贴板的操作,很方便,研究了下该效果是如何实现的,具体代码如下:
html:
<p id="select-to-copy">http://localhost:3000/account/confirmation?confirmation_token=aY2w2Yy6aVcqqd4s-oiF</p>
<button onclick="copyToClipboard('select-to-copy')">点击复制</button>
javascript:
function copyToClipboard(elementId) {
var aux = document.createElement("input");
aux.setAttribute("value", document.getElementById(elementId).innerHTML);
document.body.appendChild(aux);
aux.select();
// document.execCommand("copy");
try {
var msg = document.execCommand('copy') ? '成功' : '失败'
console.log('复制内容 ' + msg)
} catch (err) {
console.log('不能使用这种方法复制内容')
}
document.body.removeChild(aux);
}