原生JavaScript实现点击复制功能
前言
最近遇到一个需求,需要对pre标签的文本实现复制到剪切板功能,网上解决方案,大多存在兼容性问题,对某些浏览器的支持不够友好,最终搞出了一套兼容性比较好的复制功能代码。
核心JS代码
// js 复制到剪贴板
function copyToClipboard(content) {
// for ie
if (window.clipboardData) {
window.clipboardData.clearData();
window.clipboardData.setData('text', content);
}
// for modern browser
else if (document.execCommand) {
var element = document.createElement('SPAN');
element.textContent = content;
document.body.appendChild(element);
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(element);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
document.execCommand('copy');
element.remove ? element.remove() : element.removeNode(true);
}
}
Pre标签添加复制按钮
function copypre(){
[...document.getElementsByTagName("pre")].forEach(item => {
item.style.position = "relative";
let copyButton = document.createElement("button")
copyButton.innerHTML = "复制";
copyButton.onclick = function () {
copyButton.innerHTML = "";
let copyData = item.innerText;
copyToClipboard(copyData)
copyButton.innerHTML = "复制成功";
setTimeout(function() {
copyButton.innerHTML = "复制";
}, 1000);
}
item.appendChild(copyButton)
});}