未来科技研究社

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 213|回复: 0

[工具插件] 原生 js 实现点击按钮复制文本

[复制链接]

44

主题

45

帖子

870

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
870
发表于 2020-11-3 20:34:33 | 显示全部楼层 |阅读模式
一、原理分析
浏览器提供了 copy 命令 ,可以复制选中的内容
document.execCommand("copy")
如果是输入框,可以通过 select() 方法,选中输入框的文本,然后调用  copy 命令,将文本复制到剪切板
但是 select() 方法只对 <input> 和 <textarea> 有效,对于 <p> 就不好使
最后我的解决方案是,在页面中添加一个 <textarea>,然后把它隐藏掉
点击按钮的时候,先把 <textarea> 的 value 改为 <p> 的 innerText,然后复制 <textarea> 中的内容
二、代码实现
HTML 部分
[url=][/url]
<style type="text/css">   .wrapper {position: relative;}   #input {position: absolute;top: 0;left: 0;opacity: 0;z-index: -10;}</style><div class="wrapper">   <p id="text">我把你当兄弟你却想着复制我?</p>   <textarea id="input">这是幕后黑手</textarea>   <button>copy</button></div>[url=][/url]

JS 部分
[url=][/url]
  <script type="text/javascript">    function copyText() {      var text = document.getElementById("text").innerText;      var input = document.getElementById("input");      input.value = text; // 修改文本框的内容      input.select(); // 选中文本      document.execCommand("copy"); // 执行浏览器复制命令      alert("复制成功");    }  </script>[url=][/url]

亲测,Firefox 48.0,Chrome 60.0,IE 8 都能用

三、一键复制
分享一个自己工作中用到的一键复制方法
[url=][/url]
/** * 一键粘贴 * @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 的内容 */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);    }}[url=][/url]


  1. 一、原理分析

  2. 浏览器提供了 copy 命令 ,可以复制选中的内容

  3. document.execCommand("copy")
  4. 如果是输入框,可以通过 select() 方法,选中输入框的文本,然后调用  copy 命令,将文本复制到剪切板

  5. 但是 select() 方法只对 <input> 和 <textarea> 有效,对于 <p> 就不好使



  6. 最后我的解决方案是,在页面中添加一个 <textarea>,然后把它隐藏掉

  7. 点击按钮的时候,先把 <textarea> 的 value 改为 <p> 的 innerText,然后复制 <textarea> 中的内容



  8. 二、代码实现

  9. HTML 部分

  10. 复制代码
  11. <style type="text/css">
  12.    .wrapper {position: relative;}
  13.    #input {position: absolute;top: 0;left: 0;opacity: 0;z-index: -10;}
  14. </style>

  15. <div class="wrapper">
  16.    <p id="text">我把你当兄弟你却想着复制我?</p>
  17.    <textarea id="input">这是幕后黑手</textarea>
  18.    <button onclick="copyText()">copy</button>
  19. </div>
  20. 复制代码


  21. JS 部分

  22. 复制代码
  23.   <script type="text/javascript">
  24.     function copyText() {
  25.       var text = document.getElementById("text").innerText;
  26.       var input = document.getElementById("input");
  27.       input.value = text; // 修改文本框的内容
  28.       input.select(); // 选中文本
  29.       document.execCommand("copy"); // 执行浏览器复制命令
  30.       alert("复制成功");
  31.     }
  32.   </script>
  33. 复制代码


  34. 亲测,Firefox 48.0,Chrome 60.0,IE 8 都能用



  35. 三、一键复制

  36. 分享一个自己工作中用到的一键复制方法

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

  55.     if (attr) {
  56.         target = document.createElement('div');
  57.         target.id = 'tempTarget';
  58.         target.style.opacity = '0';
  59.         if (id) {
  60.             let curNode = document.querySelector('#' + id);
  61.             target.innerText = curNode[attr];
  62.         } else {
  63.             target.innerText = attr;
  64.         }
  65.         document.body.appendChild(target);
  66.     } else {
  67.         target = document.querySelector('#' + id);
  68.     }

  69.     try {
  70.         let range = document.createRange();
  71.         range.selectNode(target);
  72.         window.getSelection().removeAllRanges();
  73.         window.getSelection().addRange(range);
  74.         document.execCommand('copy');
  75.         window.getSelection().removeAllRanges();
  76.         console.log('复制成功')
  77.     } catch (e) {
  78.         console.log('复制失败')
  79.     }

  80.     if (attr) {
  81.         // remove temp target
  82.         target.parentElement.removeChild(target);
  83.     }
  84. }
  85. 复制代码
复制代码

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|未来科技研究社

GMT+8, 2025-6-5 22:27 , Processed in 0.041950 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表