写法一:
function copyToClipboard(str) {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
};
copyToClipboard('I am a lovely boy');
写法二:
function copyText(text) {
var textarea = document.createElement("input");
var currentFocus = document.activeElement;
document.body.appendChild(textarea);
textarea.value = text;
textarea.focus();
if(textarea.setSelectionRange)
textarea.setSelectionRange(0, textarea.value.length);
else
textarea.select();
try {
var flag = document.execCommand("copy");
} catch(eo) {
var flag = false;
}
document.body.removeChild(textarea);
currentFocus.focus();
return flag;
}