1. 수요 시나리오:
복사 버튼을 클릭하여 텍스트를 클립보드에 복사합니다.
2. 코드 구현:
// 브라우저와 함께 제공되는 복사 기능을 사용하여 텍스트 상자의 내용만 복사하므로 텍스트 상자를 만듭니다.
// 用浏览器自带的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. 복사할 버튼을 클릭합니다.
$('#copy-citation-btn').on('click',function () {
var textDom=$('.citation-style-item').filter(':visible');
var text = textDom.text();
if (copyTextToClipboard(text)) {
alert('复制成功!')
}
})