首页 > 解决方案 > 复制js后如何返回选择?

问题描述

文字复制功能:

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);
    }
};

哪个更好:扫描整个文档并查找设置了焦点的元素,或者将选择器传递给函数的第二个参数,您希望将选择返回到该函数,然后再次设置焦点?

标签: javascript

解决方案


推荐阅读