自己的笔记之一键复制

33 阅读1分钟

一键复制

html:
<div id="copyText">http://wwww.baidu.com</div>
<button onclick="copy(copyText)">一键复制</button>
<button @click="copy(copyText)">一键复制</button>

js:
    function copy(el) {
      var range = document.createRange();
      range.selectNode(document.getElementById(el));
      var selection = window.getSelection();
      if (selection.rangeCount > 0) selection.removeAllRanges();
      selection.addRange(range);
      document.execCommand("copy");
      // alert("复制成功");
    }