• 如何使用Javascript复制到剪贴板


    在构建网站以允许用户在某些事件中从您的网站复制文本时,您可能遇到了这种情况。我在这里有一个类似的功能来复制代码片段。

    让我们看看如何将相同的内容添加到您的网站以复制内容。

    将文本复制到剪贴板可以通过5个简单的步骤完成。

    1. 创建一个元素并将其附加到我们的 HTML 文档中。
    2. 在此中填写要复制的文本或内容
    3. 用于选择此 .HTMLElement.select()
    4. 复制使用
    5. 删除

    以下是最简单的工作版本的代码。

    1. const copyText = str => {
    2. //Create new element
    3. const elm = document.createElement('textarea');
    4. //Fill the new element with text
    5. elm.value = str;
    6. //Append the new element
    7. document.body.appendChild(elm);
    8. //Select the content of the element
    9. elm.select();
    10. //Copy the content
    11. document.execCommand('copy');
    12. //Remove the element
    13. document.body.removeChild(elm);
    14. };

    现在这是一个纯函数,它将复制事件上的内容,如 或 。你必须将文本传递给它进行复制。

    它似乎工作正常,但存在一些问题。
    1.我们添加到DOM中的元素将是可见的,这是一个糟糕的用户体验。
    用户可能已经选择了HTML文档上的一些内容,这些内容将在此操作后刷新,因此我们必须恢复原始选择。

    隐藏已连接的元素。

    我们可以设置 样式,使其在 DOM 上不可见,但仍能够执行其工作。

    1. const copyText = str => {
    2. //Create new element
    3. const elm = document.createElement('textarea');
    4. //Fill the new element with text
    5. elm.value = str;
    6. //Hiding the appended element.
    7. elm.setAttribute('readonly', '');
    8. elm.style.position = 'absolute';
    9. elm.style.left = '-9999px';
    10. //Append the new element
    11. document.body.appendChild(elm);
    12. //Select the content of the element
    13. elm.select();
    14. //Copy the content
    15. document.execCommand('copy');
    16. //Remove the element
    17. document.body.removeChild(elm);
    18. };

    恢复原始文档的选择

    用户可能已经在DOM上选择了某些内容,因此将其删除并不好。

    幸运的是,我们可以使用一些新的javascript,如DocumentOrShadowRoot.getSelection()Selection.rangeCountSelection.getRangeAt()Selection.removeAllRanges()Selection.addRange()来保存和恢复原始文档选择。

    1. const copyText = str => {
    2. //Create new element
    3. const elm = document.createElement('textarea');
    4. //Fill the new element with text
    5. elm.value = str;
    6. //Hiding the appended element.
    7. elm.setAttribute('readonly', '');
    8. elm.style.position = 'absolute';
    9. elm.style.left = '-9999px';
    10. //Append the new element
    11. document.body.appendChild(elm);
    12. // Check if there is any content selected previously
    13. const selected =
    14. document.getSelection().rangeCount > 0
    15. ? document.getSelection().getRangeAt(0) // Store selection if found
    16. : false; // Mark as false to know no selection existed before
    17. // Select the <textarea> content
    18. el.select();
    19. // Copy - only works as a result of a user action (e.g. click events)
    20. document.execCommand('copy');
    21. // Remove the <textarea> element
    22. document.body.removeChild(el);
    23. // If a selection existed before copying
    24. if (selected) {
    25. document.getSelection().removeAllRanges(); // Unselect everything on the HTML document
    26. document.getSelection().addRange(selected); // Restore the original selection
    27. }
    28. };

    如果您想通过直接单击或对其执行操作来将文本复制到javascript中的剪贴板,则还有另一种方法。

    剪贴板 API 在对象上可用。navigator.clipboard

    剪贴板 API 是相对较新的,并非所有浏览器都实现它。它适用于Chrome,现代Edge(基于chromium),Firefox和Opera。

    我们可以检查它是否受支持。

    1. if (!navigator.clipboard) {
    2. // Clipboard API not available
    3. return
    4. }

    您现在必须了解的一件事是,未经用户许可,您无法从剪贴板复制/粘贴。

    如果您正在阅读或写入剪贴板,则权限会有所不同。如果您正在编写,您所需要的只是用户的意图:您需要将剪贴板操作放在对用户操作的响应中,例如单击。

    将文本写入剪贴板

    假设我们有一个段落元素,我们想要复制其内容。

    <p>Master DSA with Javascript</p>

    当我们单击此文本时,我们希望将其复制到剪贴板上。因此,我们为其分配一个事件侦听器。

    1. document.querySelector('p').addEventListener('click', async event => {
    2. if (!navigator.clipboard) {
    3. // Clipboard API not available
    4. return;
    5. }
    6. });

    然后,我们调用并将段落元素的文本复制到剪贴板。由于这是一个异步进程,我们将使用异步/等待。navigator.clipboard.writeText()

    1. document.querySelector('p').addEventListener('click', async event => {
    2. if (!navigator.clipboard) {
    3. // Clipboard API not available
    4. return;
    5. }
    6. //Get the paragraph text
    7. const text = event.target.innerText
    8. try {
    9. //Write it to the clipboard
    10. await navigator.clipboard.writeText(text);
    11. //Change text to notify user
    12. event.target.textContent = 'Copied to clipboard';
    13. } catch (err) {
    14. console.error('Failed to copy!', err);
    15. }
    16. })

    在剪贴板上编写内容后,我们也可以从那里阅读它。


    从剪贴板读取文本

    从剪贴板获取复制的内容。

    <p>Master Full stack development with Javascript</p>

    当我们单击此文本时,我们希望将其从我们复制的内容中更改。

    1. document.querySelector('p').addEventListener('click', async event => {
    2. if (!navigator.clipboard) {
    3. // Clipboard API not available
    4. return;
    5. }
    6. });

    然后,我们调用并从剪贴板获取复制的文本。由于这是一个异步进程,我们将使用异步/等待。navigator.clipboard.readText()

    1. document.querySelector('p').addEventListener('click', async event => {
    2. if (!navigator.clipboard) {
    3. // Clipboard API not available
    4. return;
    5. }
    6. try {
    7. //Get the copied text
    8. const text = await navigator.clipboard.readText();
    9. //Pass it to the element.
    10. event.target.textContent = text;
    11. } catch (err) {
    12. console.error('Failed to copy!', err);
    13. }
    14. });

  • 相关阅读:
    计算机网络安全隔离之网闸、光闸
    AT24C02芯片
    【每日一题】二叉搜索树的后序遍历序列
    Dijkstra、A*算法python实现及对比分析
    Kubernetes容器状态探测的艺术
    autojs操作
    Linux常用命令大全(非常全!!!)
    Docker-harbor私有仓库部署与管理
    卷积层与池化层输出的尺寸的计算公式详解
    Golang Web框架还在用Gin吗,快试试全新框架Bud吧
  • 原文地址:https://blog.csdn.net/qq_22182989/article/details/125625151