一、需求场景:
点击复制按钮,复制文字到剪切板
二、代码实现:
// 用浏览器自带的copy功能只能复制文本框里面的内容,因此要创建文本框
// 用浏览器自带的copy功能只能复制文本框里面的内容,因此要创建文本框
function fallbackCopyTextToClipboard(text) {
var result, textArea;
textArea = document.createElement("textarea");
textArea.value = text;
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
result = document.execCommand('copy');
document.body.removeChild(textArea);
return result;
}
// 复制到剪切板
function copyTextToClipboard(text) {
if (navigator.clipboard) {
return navigator.clipboard.writeText(text);
} else {
return fallbackCopyTextToClipboard(text);
}
};
三、点击按钮复制:
$('#copy-citation-btn').on('click',function () {
var textDom=$('.citation-style-item').filter(':visible');
var text = textDom.text();
if (copyTextToClipboard(text)) {
alert('复制成功!')
}
})