1. Demand scenario:
Click the copy button to copy the text to the clipboard
2. Code implementation:
// Use the copy function that comes with the browser to only copy the contents of the text box, so create a text box
// 用浏览器自带的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);
}
};
3. Click the button to copy:
$('#copy-citation-btn').on('click',function () {
var textDom=$('.citation-style-item').filter(':visible');
var text = textDom.text();
if (copyTextToClipboard(text)) {
alert('复制成功!')
}
})