提问,实现点击复制功能

原生的JavaScript怎么实现点击复制功能,但是不能使用 document.execCommand 因为它已经弃用


/**
 * 一键粘贴
 * @param  {String} id [需要粘贴的内容]
 * @param  {String} attr [需要 copy 的属性,默认是 innerText,主要用途例如赋值 a 标签上的 href 链接]
 *
 * range + selection
 *
 * 1.创建一个 range
 * 2.把内容放入 range
 * 3.把 range 放入 selection
 *
 * 注意:参数 attr 不能是自定义属性
 * 注意:对于 user-select: none 的元素无效
 * 注意:当 id false 且 attr 不会空,会直接复制 attr 的内容
 */
function copy (id, attr) {
    let target = null;

    if (attr) {
        target = document.createElement('div');
        target.id = 'tempTarget';
        target.style.opacity = '0';
        if (id) {
            let curNode = document.querySelector('#' + id);
            target.innerText = curNode[attr];
        } else {
            target.innerText = attr;
        }
        document.body.appendChild(target);
    } else {
        target = document.querySelector('#' + id);
    }

    try {
        let range = document.createRange();
        range.selectNode(target);
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
        document.execCommand('copy');
        window.getSelection().removeAllRanges();
        console.log('复制成功')
    } catch (e) {
        console.log('复制失败')
    }

    if (attr) {
        // remove temp target
        target.parentElement.removeChild(target);
    }
}

推荐你参考下下面这篇文章


<!--引入插件-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.7.1/clipboard.min.js"></script>
<script type="text/javascript">
$('#copy').on('click', function () {
  var value = $('#copyTkl').val();
  $('#copyTkl').attr('data-clipboard-text', value);
  var clipboard = new Clipboard('#copyTkl');
  clipboard.on('success', function (e) {
    alert("复制淘口令成功......");
  });
  clipboard.on('error', function (e) {
    alert("复制淘口令失败......");
  });
})
</script>