Javascript 复制js后如何返回选择?
文本复制功能:Javascript 复制js后如何返回选择?,javascript,Javascript,文本复制功能: 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);
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);
}
};
哪一个更好:扫描整个文档并查找设置了焦点的元素,或者将选择器传递给函数您要返回选择的第二个参数,然后再次在那里设置焦点