使用JavaScript将文本复制到剪贴板

在本文中,我将深入解释 30秒代码中 的copyToClipboard代码段如何 工作。 您可以在项目的存储库中找到它的源代码以及大量其他有用的方法。

30秒的代码:您可以在30秒或更短的时间内理解的Java 代码片段

网站建设中经常出现的一件事是能够将一些文本复制到剪贴板,而无需用户选择它或敲击键盘上的适当组合键。 Javascript可以通过五个短步轻松完成此操作:

  1. 创建一个<textarea>元素添加到文档中。 将其value设置为我们要复制到剪贴板的字符串。
  2. 将所述<textarea>元素追加到当前HTML文档中。
  3. 使用HTMLInputElement.select()选择<textarea>元素的内容。
  4. 使用Document.execCommand('copy')<textarea>的内容复制到剪贴板。
  5. 从文档中删除<textarea>元素。

此方法的最简单版本应如下所示:

const copyToClipboard = str => {
  const el = document .createElement( 'textarea' );
  el.value = str;
  document .body.appendChild(el);
  el.select();
  document .execCommand( 'copy' );
  document .body.removeChild(el);
};

(copyToClipboard方法的基本实现)

请记住,由于Document.execCommand()工作方式,该方法不会在所有地方都有效,而只能是由于用户操作(例如在click事件侦听器内部)导致的。

使附加元素不可见

如果尝试上述方法,则在添加<textarea>元素然后将其删除后,可能会看到一些闪烁。 这个问题对于在屏幕阅读器上的人们来说尤其糟糕,因为它可能会引起一些非常烦人的问题。 因此,下一步的逻辑步骤是使用一些CSS使该元素不可见,并将其变为readonly ,以防用户尝试弄乱它:

const 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);
  el.select();
  document .execCommand( 'copy' );
  document .body.removeChild(el);
};

(没有显示文本区域的copyToClipboard实现)

保存和还原原始文档的选择

最后要考虑的是,用户可能已经选择了HTML文档上的某些内容,因此最好不要删除他们可能选择的任何内容。 幸运的是,我们现在可以使用一些现代的Javascript方法和属性,例如DocumentOrShadowRoot.getSelection()Selection.rangeCountSelection.getRangeAt()Selection.removeAllRanges()Selection.addRange()来保存和恢复原始文档选择。 这是实现这些改进的带有注释的最终代码:


const copyToClipboard = str => {
  const el = document .createElement( 'textarea' );  // Create a <textarea> element
  el.value = str;                                 // Set its value to the string that you want copied
  el.setAttribute( 'readonly' , '' );                // Make it readonly to be tamper-proof
  el.style.position = 'absolute' ;                 
  el.style.left = '-9999px' ;                      // Move outside the screen to make it invisible
  document .body.appendChild(el);                  // Append the <textarea> element to the HTML document
  const selected =            
    document .getSelection().rangeCount > 0        // Check if there is any content selected previously
      ? document .getSelection().getRangeAt( 0 )     // Store selection if found
      : false ;                                    // Mark as false to know no selection existed before
  el.select();                                    // Select the <textarea> content
  document .execCommand( 'copy' );                   // Copy - only works as a result of a user action (e.g. click events)
  document .body.removeChild(el);                  // Remove the <textarea> element
  if (selected) {                                 // If a selection existed before copying
    document .getSelection().removeAllRanges();    // Unselect everything on the HTML document
    document .getSelection().addRange(selected);   // Restore the original selection
  }
};

(带有选择存储的copyToClipboard的最终形式)

这几乎就是它的全部。 在不到20行的代码中,我们创建了前端开发中最常用的方法之一。

如果您喜欢本文,请查看 30秒的代码, 以获取有关Javascript项目的更有用的代码段!

From: https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值