【问题标题】:Click button copy to clipboard单击按钮复制到剪贴板
【发布时间】:2014-04-30 03:41:07
【问题描述】:

如何将 div 中的文本复制到剪贴板?我有一个 div,需要添加一个链接,将文本添加到剪贴板。有解决方案吗?

<p class="content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p>

<a class="copy-text">copy Text</a>

点击复制文本后,再按Ctrl + V,必须粘贴。

【问题讨论】:

  • Trello 有一个聪明的方法可以在没有 Flash 的情况下做到这一点:stackoverflow.com/questions/17527870/…
  • 参考这个,stackoverflow.com/questions/22581345/… 使用纯 JavaScript 得到了预期的解决方案
  • @MichaelScheper - 一些用户甚至足够聪明地注意到我的评论以及这里的大部分答案都是四年前发布的,当时基于小型 Flash 应用程序的 zeroclipboard 是使用剪贴板和 goto 解决方案的唯一跨浏览器可行选项。今天,所有现代浏览器都原生支持这一点,所以这不再是一个问题,但在 2014 年并非如此
  • @MichaelScheper - 您的评论并没有显得过于挑剔,而是显得完全放错地方和居高临下。评论 “Seriously no ... flash is evil, users know better ..” 四年后,似乎完全多余,我们都知道没有人再使用 flash,它不是在所有平台上都支持等等,而且下面的答案已更新以反映这一点。然而,当这些答案和我的评论首次发布时,flash 是这个问题的唯一可行答案,因此我的评论是站得住脚的,即使只是出于历史目的。完全没有必要删除它,

标签: jquery html css


【解决方案1】:

2020 年更新:此解决方案使用 execCommand。虽然在撰写此答案时该功能很好,it is now considered obsolete。它仍然适用于许多浏览器,但不鼓励使用它,因为可能会放弃支持。

还有另一种非Flash方式(除了jfriend00's answer中提到的Clipboard API)。您需要选择文本,然后execute the command copy 将页面上当前选择的任何文本复制到剪贴板。

例如,此函数会将传递的元素的内容复制到剪贴板(使用来自PointZeroTwo 的 cmets 中的建议进行更新):

function copyToClipboard(element) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($(element).text()).select();
    document.execCommand("copy");
    $temp.remove();
}

这就是它的工作原理:

  1. 创建一个临时隐藏的文本字段。
  2. 将元素的内容复制到该文本字段。
  3. 选择文本字段的内容。
  4. 执行命令复制,如:document.execCommand("copy")
  5. 删除临时文本字段。

注意元素的内部文本可以包含空格。因此,如果您想使用 if 作为密码,您可以在上面的代码中使用 $(element).text().trim() 来修剪文本。

您可以在此处查看快速演示:

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="p1">P1: I am paragraph 1</p>
<p id="p2">P2: I am a second paragraph</p>
<button onclick="copyToClipboard('#p1')">Copy P1</button>
<button onclick="copyToClipboard('#p2')">Copy P2</button>
<br/><br/><input type="text" placeholder="Paste here for test" />

主要问题是目前并非所有browsers support 都有此功能,但您可以在以下主要功能上使用它:

  • 铬 43
  • Internet Explorer 10
  • 火狐41
  • Safari 10

更新 1:这也可以通过纯 JavaScript 解决方案(无 jQuery)来实现:

function copyToClipboard(elementId) {

  // Create a "hidden" input
  var aux = document.createElement("input");

  // Assign it the value of the specified element
  aux.setAttribute("value", document.getElementById(elementId).innerHTML);

  // Append it to the body
  document.body.appendChild(aux);

  // Highlight its content
  aux.select();

  // Copy the highlighted text
  document.execCommand("copy");

  // Remove it from the body
  document.body.removeChild(aux);

}
<p id="p1">P1: I am paragraph 1</p>
<p id="p2">P2: I am a second paragraph</p>
<button onclick="copyToClipboard('p1')">Copy P1</button>
<button onclick="copyToClipboard('p2')">Copy P2</button>
<br/><br/><input type="text" placeholder="Paste here for test" />

请注意,我们现在传递的 id 不带 #。

正如madzohan 在下面的 cmets 中报告的那样,在某些情况下(在本地运行文件),64 位版本的 Google Chrome 存在一些奇怪的问题。上面的非 jQuery 解决方案似乎解决了这个问题。

Madzohan 在 Safari 中尝试过,并且解决方案有效,但使用 document.execCommand('SelectAll') 而不是使用 .select()(在聊天和下面的 cmets 中指定)。

作为PointZeroTwo points out in the comments,可以改进代码,使其返回成功/失败结果。您可以在this jsFiddle 上查看演示。


更新:复制保持文本格式

作为user pointed out in the Spanish version of StackOverflow,如果您想从字面上复制元素的内容,上面列出的解决方案非常有效,但如果您想粘贴带有格式的复制文本(因为它被复制转换成input type="text",格式为“丢失”)。

解决方案是复制到可编辑的内容div,然后以类似的方式使用execCommand 复制它。这里有一个例子——点击复制按钮,然后粘贴到下面的内容可编辑框中:

function copy(element_id){
  var aux = document.createElement("div");
  aux.setAttribute("contentEditable", true);
  aux.innerHTML = document.getElementById(element_id).innerHTML;
  aux.setAttribute("onfocus", "document.execCommand('selectAll',false,null)"); 
  document.body.appendChild(aux);
  aux.focus();
  document.execCommand("copy");
  document.body.removeChild(aux);
}
#target {
  width:400px;
  height:100px;
  border:1px solid #ccc;
}
<p id="demo"><b>Bold text</b> and <u>underlined text</u>.</p>
<button onclick="copy('demo')">Copy Keeping Format</button> 

<div id="target" contentEditable="true"></div>

在 jQuery 中,它会是这样的:

function copy(selector){
  var $temp = $("<div>");
  $("body").append($temp);
  $temp.attr("contenteditable", true)
       .html($(selector).html()).select()
       .on("focus", function() { document.execCommand('selectAll',false,null); })
       .focus();
  document.execCommand("copy");
  $temp.remove();
}
#target {
  width:400px;
  height:100px;
  border:1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p id="demo"><b>Bold text</b> and <u>underlined text</u>.</p>
<button onclick="copy('#demo')">Copy Keeping Format</button> 

<div id="target" contentEditable="true"></div>

【讨论】:

  • 奇怪......在这里它可以工作,但我无法在本地工作 0o jquery-1.11.3 Chrome 43.0.2357.130(64 位)
  • @madzohan 好的,我能够重现该问题。这很奇怪,因为我只能在 64 位 Chrome 上的本地 (file://) 上重现它。我还找到了一个适合我的快速解决方案:使用纯 JavaScript 而不是 jQuery。我将使用该代码更新答案。请检查一下,让我知道它是否适合您。
  • FWIW - document.execCommand("copy") 返回一个布尔值(IE、Chrome、Safari),指示复制是否成功。它可用于在失败时显示错误消息。 Firefox 在失败时抛出异常(至少在 v39 中),需要 try/catch 来处理错误。
  • 这对我不起作用,直到我通过添加以下行来确保 aux 在页面上可见:aux.style.position = "fixed"; aux.style.top = 0;appendChild 调用上方。
  • 原始 jQuery 实现未能保留换行符,因为它使用了 INPUT 元素。使用 TEXTAREA 可以解决这个问题。
【解决方案2】:

自 2016 年起编辑

从 2016 年开始,您现在可以在大多数浏览器中将文本复制到剪贴板,因为大多数浏览器都能够使用 document.execCommand("copy") 以编程方式将选定的文本复制到剪贴板,这对选定内容起作用。

与浏览器中的其他一些操作(例如打开新窗口)一样,复制到剪贴板只能通过特定的用户操作(例如单击鼠标)来完成。例如,它不能通过计时器来完成。

这是一个代码示例:

document.getElementById("copyButton").addEventListener("click", function() {
    copyToClipboard(document.getElementById("copyTarget"));
});

function copyToClipboard(elem) {
	  // create hidden text element, if it doesn't already exist
    var targetId = "_hiddenCopyText_";
    var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
    var origSelectionStart, origSelectionEnd;
    if (isInput) {
        // can just use the original source element for the selection and copy
        target = elem;
        origSelectionStart = elem.selectionStart;
        origSelectionEnd = elem.selectionEnd;
    } else {
        // must use a temporary form element for the selection and copy
        target = document.getElementById(targetId);
        if (!target) {
            var target = document.createElement("textarea");
            target.style.position = "absolute";
            target.style.left = "-9999px";
            target.style.top = "0";
            target.id = targetId;
            document.body.appendChild(target);
        }
        target.textContent = elem.textContent;
    }
    // select the content
    var currentFocus = document.activeElement;
    target.focus();
    target.setSelectionRange(0, target.value.length);
    
    // copy the selection
    var succeed;
    try {
    	  succeed = document.execCommand("copy");
    } catch(e) {
        succeed = false;
    }
    // restore original focus
    if (currentFocus && typeof currentFocus.focus === "function") {
        currentFocus.focus();
    }
    
    if (isInput) {
        // restore prior selection
        elem.setSelectionRange(origSelectionStart, origSelectionEnd);
    } else {
        // clear temporary content
        target.textContent = "";
    }
    return succeed;
}
input {
  width: 400px;
}
<input type="text" id="copyTarget" value="Text to Copy"> <button id="copyButton">Copy</button><br><br>
<input type="text" placeholder="Click here and press Ctrl-V to see clipboard contents">

这里有一个更高级的演示:https://jsfiddle.net/jfriend00/v9g1x0o6/

而且,您还可以使用 clipboard.js 获得一个为您执行此操作的预构建库。


答案的旧的历史部分

出于安全原因,任何现代浏览器都不允许通过 JavaScript 直接复制到剪贴板。最常见的解决方法是使用 Flash 功能复制到剪贴板,该功能只能由用户直接点击触发。

如前所述,ZeroClipboard 是一组流行的代码,用于管理 Flash 对象以进行复制。我用过。如果浏览设备(不包括移动设备或平板电脑)上安装了 Flash,则它可以工作。


下一个最常见的解决方法是将剪贴板绑定的文本放入输入字段,将焦点移至该字段并建议用户按 Ctrl + C 复制文本。

可以在之前的 Stack Overflow 帖子中找到有关该问题的其他讨论和可能的解决方法:


这些要求以现代方式替代使用 Flash 的问题已收到很多问题的支持,但没有任何解决方案的答案(可能是因为不存在):


Internet Explorer 和 Firefox 曾经有用于访问剪贴板的非标准 API,但它们更现代的版本已弃用这些方法(可能出于安全原因)。


有一个nascent standards effort 试图提出一种“安全”的方法来解决最常见的剪贴板问题(可能需要像 Flash 解决方案一样需要特定的用户操作),并且看起来它可能已部分实现在最新版本的 Firefox 和 Chrome 中,但我尚未确认。

【讨论】:

  • clipboard.js 刚刚添加到此编辑后的帖子中。这是一个很好的实用程序,我在 2015 年 8 月将其作为这个问题的答案。
  • @acoder - 剪贴板支持一直在定期更改。例如,Firefox 仅在最近(2015 年末)在足够的情况下启用了document.execCommand("copy"),以依赖它来实现这一点。因此,我正在努力使我的答案保持最新(最初是在大约 2 年前撰写的)。除了预先选择文本并告诉用户手动按 Ctrl+C 之外,我们还没有针对 Safari 的可靠解决方案,但至少在其他方面正在取得进展。
  • 这里是支持剪贴板 API 的链接:caniuse.com/#feat=clipboard
  • 仅供参考,根据this set of Safari release notes,Safari 10 现在似乎支持document.execCommand("copy"),所以这段代码现在应该可以在 Safari 10 中使用。
  • @sebastiangodelet - 公共领域。
【解决方案3】:

更新:现在正确的做法是使用Clipboard API

例如:

// get the text from the DOM Element: 
const textToCopy = document.querySelector('.content').innerText

// when someone clicks on the <a class="copy-text"> element 
// (which should be a <button>), execute the copy command:
document.querySelector('.copy-text').addEventListener('click' , ()=> {
  navigator.clipboard.writeText(textToCopy).then(
    function() {
      /* clipboard successfully set */
      window.alert('Success! The text was copied to your clipboard') 
    }, 
    function() {
      /* clipboard write failed */
      window.alert('Opps! Your browser does not support the Clipboard API')
    }
  )
})

就是这样。



如果您想在引入剪贴板 API 之前查看解决方案(现在不是一个好的做法):

$('button.copyButton').click(function(){
    $(this).siblings('input.linkToCopy').select();      
    document.execCommand("copy");
});

HTML:

<button class="copyButton">click here to copy</button>
<input class="linkToCopy" value="TEXT TO COPY"
style="position: absolute; z-index: -999; opacity: 0;" />

【讨论】:

  • 似乎不适用于 ipad,尚未测试,但建议的解决方案在这里:stackoverflow.com/a/34046084
  • 这对我有用,但是如果要复制的文本包含回车,那么您也可以使用 textarea 代替。
【解决方案4】:

从 2022 年起,您应该使用 Clipboard Api

navigator.clipboard.writeText('text here you want to copy').then(function () {
    alert('It worked! Do a CTRL - V to paste')
}, function () {
    alert('Failure to copy. Check permissions for clipboard')
});

这里有更多关于interacting with the clipboard的信息

【讨论】:

    【解决方案5】:

    clipboard.js 是一个不错的实用程序,它允许在不使用 Flash 的情况下将文本或 HTML 数据复制到剪贴板。它非常易于使用;只需包含 .js 并使用如下内容:

    <button id='markup-copy'>Copy Button</button>
    
    <script>
        document.getElementById('markup-copy').addEventListener('click', function() {
            clipboard.copy({
                'text/plain': 'Markup text. Paste me into a rich text editor.',
                'text/html': '<i>here</i> is some <b>rich text</b>'
            }).then(
                function(){console.log('success'); },
                function(err){console.log('failure', err);
            });
        });
    </script>
    

    clipboard.js is also on GitHub.

    2016 年 1 月 15 日编辑:top answer 今天是 edited,以引用我在 2015 年 8 月发布的答案中的相同 API。之前的文字是指导用户使用 ZeroClipboard。只是想明确一点,我没有从 jfriend00 的答案中抽出这个,而是相反。

    【讨论】:

    【解决方案6】:

    带有换行符(Alvaro Montoro 答案的扩展)

    var ClipboardHelper = {
    
        copyElement: function ($element)
        {
           this.copyText($element.text())
        },
        copyText:function(text) // Linebreaks with \n
        {
            var $tempInput =  $("<textarea>");
            $("body").append($tempInput);
            $tempInput.val(text).select();
            document.execCommand("copy");
            $tempInput.remove();
        }
    };
    
    ClipboardHelper.copyText('Hello\nWorld');
    ClipboardHelper.copyElement($('body h1').first());
    

    【讨论】:

      【解决方案7】:

      没有闪存或任何其他要求的更好方法是clipboard.js。您需要做的就是在任何按钮上添加data-clipboard-target="#toCopyElement",初始化它new Clipboard('.btn');,它会将id为toCopyElement的DOM内容复制到剪贴板。这是一个 sn-p,它通过链接复制您问题中提供的文本。

      一个限制是它不适用于 safari,但它适用于所有其他浏览器,包括移动浏览器,因为它不使用 flash

      $(function(){
        new Clipboard('.copy-text');
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <script src="https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js"></script>
      
      <p id="content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p>
      
      <a class="copy-text" data-clipboard-target="#content" href="#">copy Text</a>

      【讨论】:

        【解决方案8】:
        <div class="form-group">
            <label class="font-normal MyText">MyText to copy</label>&nbsp;
            <button type="button" class="btn btn-default btn-xs btnCopy" data="MyText">Copy</button>
        </div>
        
        
        $(".btnCopy").click(function () {
                var element = $(this).attr("data");
                copyToClipboard($('.' + element));
          });
        
        function copyToClipboard(element) {
            var $temp = $("<input>");
            $("body").append($temp);
            $temp.val($(element).text()).select();
            document.execCommand("copy");
            $temp.remove();
        }
        

        【讨论】:

        • 不错的解决方法。也许将.addClass("hidden") 添加到&lt;input&gt; 标记以使其永远不会显示在浏览器中?
        【解决方案9】:

        jQuery 简单解决方案。

        应该由用户点击触发。

        $("<textarea/>").appendTo("body").val(text).select().each(function () {
                    document.execCommand('copy');
                }).remove();
        

        【讨论】:

          【解决方案10】:

          您可以使用此代码通过单击按钮在剪贴板中的页面中复制输入值

          这是HTML

          <input type="text" value="xxx" id="link" class="span12" />
          <button type="button" class="btn btn-info btn-sm" onclick="copyToClipboard('#link')">
              Copy Input Value
          </button>
          

          那么对于这个html,我们必须使用这个JQuery Code

          function copyToClipboard(element) {
              $(element).select();
              document.execCommand("copy");
          }
          

          这是这个问题最简单的解决方案

          【讨论】:

            【解决方案11】:
            <!DOCTYPE html>
            <html>
            <head>
                <title></title>
                <link href="css/index.css" rel="stylesheet" />
                <script src="js/jquery-2.1.4.min.js"></script>
                <script>
                    function copy()
                    {
                        try
                        {
                            $('#txt').select();
                            document.execCommand('copy');
                        }
                        catch(e)
                        {
                            alert(e);
                        }
                    }
                </script>
            </head>
            <body>
                <h4 align="center">Copy your code</h4>
                <textarea id="txt" style="width:100%;height:300px;"></textarea>
                <br /><br /><br />
                <div align="center"><span class="btn-md" onclick="copy();">copy</span></div>
            </body>
            </html>
            

            【讨论】:

            • 这只能用于Textarea和textbox。
            【解决方案12】:

            输入字段没有display: none 非常重要。浏览器不会选择文本,因此不会被复制。使用宽度为 0px 的opacity: 0 解决问题。

            【讨论】:

              【解决方案13】:
              <p style="color:wheat;font-size:55px;text-align:center;">How to copy a TEXT to Clipboard on a Button-Click</p>
                  
                  <center>
                  <p id="p1">Hello, I'm TEXT 1</p>
                  <p id="p2">Hi, I'm the 2nd TEXT</p><br/>
                  
                  <button onclick="copyToClipboard('#p1')">Copy TEXT 1</button>
                  <button onclick="copyToClipboard('#p2')">Copy TEXT 2</button>
                    
                  </center>
              
              <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
              <script>
                  function copyToClipboard(element) {
                    var $temp = $("<input>");
                    $("body").append($temp);
                    $temp.val($(element).text()).select();
                    document.execCommand("copy");
                    $temp.remove();
                  }
              </script>
              

              【讨论】:

                【解决方案14】:

                复制内容是最简单的方法

                 <div id="content"> Lorepm ispum </div>
                 <button class="copy" title="content">Copy Sorce</button>
                
                function SelectContent(element) {
                                        var doc = document
                                            , text = doc.getElementById(element)
                                            , range, selection
                                        ;    
                                        if (doc.body.createTextRange) {
                                            range = document.body.createTextRange();
                                            range.moveToElementText(text);
                                            range.select();
                                        } else if (window.getSelection) {
                                            selection = window.getSelection();        
                                            range = document.createRange();
                                            range.selectNodeContents(text);
                                            selection.removeAllRanges();
                                            selection.addRange(range);
                
                                        }
                                         document.execCommand('Copy');
                                    }
                                    $(".copy").click(function(){
                
                                         SelectContent( $(this).attr('title'));
                                    });
                

                【讨论】:

                  【解决方案15】:

                  大多数建议的答案都会创建一个额外的临时隐藏输入元素。因为现在大多数浏览器都支持 div 内容编辑,所以我提出了一个不创建隐藏元素、保留文本格式并使用纯 JavaScript 或 jQuery 库的解决方案。

                  这是一个使用我能想到的最少代码行的极简骨架实现:

                  //Pure javascript implementation:
                  document.getElementById("copyUsingPureJS").addEventListener("click", function() {
                    copyUsingPureJS(document.getElementById("copyTarget"));
                    alert("Text Copied to Clipboard Using Pure Javascript");
                  });
                  
                  function copyUsingPureJS(element_id) {
                    element_id.setAttribute("contentEditable", true);
                    element_id.setAttribute("onfocus", "document.execCommand('selectAll',false,null)");
                    element_id.focus();
                    document.execCommand("copy");
                    element_id.removeAttribute("contentEditable");
                    
                  }
                  
                  //Jquery:
                  $(document).ready(function() {
                    $("#copyUsingJquery").click(function() {
                      copyUsingJquery("#copyTarget");
                    });
                   
                  
                    function copyUsingJquery(element_id) {
                      $(element_id).attr("contenteditable", true)
                        .select()
                        .on("focus", function() {
                          document.execCommand('selectAll', false, null)
                        })
                        .focus()
                      document.execCommand("Copy");
                      $(element_id).removeAttr("contenteditable");
                       alert("Text Copied to Clipboard Using jQuery");
                    }
                  });
                  #copyTarget {
                    width: 400px;
                    height: 400px;
                    border: 1px groove gray;
                    color: navy;
                    text-align: center;
                    box-shadow: 0 4px 8px 0 gray;
                  }
                  
                  #copyTarget h1 {
                    color: blue;
                  }
                  
                  #copyTarget h2 {
                    color: red;
                  }
                  
                  #copyTarget h3 {
                    color: green;
                  }
                  
                  #copyTarget h4 {
                    color: cyan;
                  }
                  
                  #copyTarget h5 {
                    color: brown;
                  }
                  
                  #copyTarget h6 {
                    color: teal;
                  }
                  
                  #pasteTarget {
                    width: 400px;
                    height: 400px;
                    border: 1px inset skyblue;
                  }
                  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                  <div id="copyTarget">
                    <h1>Heading 1</h1>
                    <h2>Heading 2</h2>
                    <h3>Heading 3</h3>
                    <h4>Heading 4</h4>
                    <h5>Heading 5</h5>
                    <h6>Heading 6</h6>
                    <strong>Preserve <em>formatting</em></strong>
                    <br/>
                  </div>
                  
                  <button id="copyUsingPureJS">Copy Using Pure JavaScript</button>
                  <button id="copyUsingJquery">Copy Using jQuery</button>
                  <br><br> Paste Here to See Result
                  <div id="pasteTarget" contenteditable="true"></div>

                  【讨论】:

                    【解决方案16】:

                    要复制的文本在文本输入中,例如:&lt;input type="text" id="copyText" name="copyText"&gt; 并且,在按钮上单击上面的文本应该被复制到剪贴板,所以按钮类似于:&lt;button type="submit" id="copy_button" data-clipboard-target='copyText'&gt;Copy&lt;/button&gt; 你的脚本应该是这样的:

                    <script language="JavaScript">
                    $(document).ready(function() {
                    var clip = new ZeroClipboard($("#copy_button"), {
                      moviePath: "ZeroClipboard.swf"
                    }); 
                    });
                    
                    </script>
                    

                    对于 CDN 文件

                    注意ZeroClipboard.swfZeroClipboard.js" 文件应与使用此功能的文件位于同一文件夹中,或者您必须像我们在页面上包含 &lt;script src=""&gt;&lt;/script&gt; 一样包含。

                    【讨论】:

                    • Flash 正在走上 Geocities 的道路。
                    【解决方案17】:

                    您可以使用这个库轻松实现复制目标!

                    https://clipboardjs.com/

                    将文本复制到剪贴板应该不难。它不应该要求 数十个步骤来配置或数百 KB 加载。但大多数 总而言之,它不应该依赖于 Flash 或任何臃肿的框架。

                    这就是 clipboard.js 存在的原因。

                    https://github.com/zeroclipboard/zeroclipboard

                    http://zeroclipboard.org/

                    ZeroClipboard 库提供了一种将文本复制到 使用不可见的 Adob​​e Flash 影片和 JavaScript 的剪贴板 界面。

                    【讨论】:

                      【解决方案18】:

                      Clipboard-polyfill 库是现代基于 Promise 的异步剪贴板 API 的 polyfill。

                      在 CLI 中安装:

                      npm install clipboard-polyfill 
                      

                      在 JS 文件中作为剪贴板导入

                      window.clipboard = require('clipboard-polyfill');
                      

                      example

                      我将它与 require("babel-polyfill"); 捆绑使用,并在 chrome 67 上对其进行了测试。一切都适合生产。

                      【讨论】:

                        【解决方案19】:

                        这里是html代码

                            <input id="result" style="width:300px"/>some example text
                            <button onclick="copyToClipboard('result')">Copy P1</button>
                            <input type="text" style="width:400px" placeholder="Paste here for test" />
                        

                        JS代码:

                             function copyToClipboard(elementId) {
                        
                                              // Create a "hidden" input
                                              var aux = document.createElement("input");
                        
                                              aux.setAttribute("value", document.getElementById(elementId).value);
                                              // Append it to the body
                                              document.body.appendChild(aux);
                                              // Highlight its content
                                              aux.select();
                                              // Copy the highlighted text
                                              document.execCommand("copy");
                                              // Remove it from the body
                                              document.body.removeChild(aux);
                                            }
                        

                        【讨论】:

                        • 改变这个:.value 到 .innerHTML
                        【解决方案20】:

                        除了 HTML 元素的文本之外,您还可以复制单个文本。

                                var copyToClipboard = function (text) {
                                    var $txt = $('<textarea />');
                        
                                    $txt.val(text)
                                        .css({ width: "1px", height: "1px" })
                                        .appendTo('body');
                        
                                    $txt.select();
                        
                                    if (document.execCommand('copy')) {
                                        $txt.remove();
                                    }
                                };
                        

                        【讨论】:

                          【解决方案21】:

                          纯 JS,没有内联 onclick,用于配对类“内容 - 复制按钮”。如果你有很多元素会更舒服)

                          (function(){
                          
                          /* Creating textarea only once, but not each time */
                          let area = document.createElement('textarea');
                          document.body.appendChild( area );
                          area.style.display = "none";
                          
                          let content = document.querySelectorAll('.js-content');
                          let copy    = document.querySelectorAll('.js-copy');
                          
                          for( let i = 0; i < copy.length; i++ ){
                            copy[i].addEventListener('click', function(){
                              area.style.display = "block";
                              /* because the classes are paired, we can use the [i] index from the clicked button,
                              to get the required text block */
                              area.value = content[i].innerText;
                              area.select();
                              document.execCommand('copy');   
                              area.style.display = "none";
                          
                              /* decorative part */
                              this.innerHTML = 'Cop<span style="color: red;">ied</span>';
                              /* arrow function doesn't modify 'this', here it's still the clicked button */
                              setTimeout( () => this.innerHTML = "Copy", 2000 );
                            });
                          }
                          
                          })();
                          hr { margin: 15px 0; border: none; }
                          <span class="js-content">1111</span>
                          <button class="js-copy">Copy</button>
                          <hr>
                          <span class="js-content">2222</span>
                          <button class="js-copy">Copy</button>
                          <hr>
                          <span class="js-content">3333</span>
                          <button class="js-copy">Copy</button>

                          旧版浏览器支持:

                          (function(){
                          
                          var area = document.createElement('textarea');
                          document.body.appendChild( area );
                          area.style.display = "none";
                          
                          var content = document.querySelectorAll('.js-content');
                          var copy    = document.querySelectorAll('.js-copy');
                          
                          for( var i = 0; i < copy.length; i++ ){
                            copyOnClick(i);
                          }
                          
                          function copyOnClick(i){
                            copy[i].addEventListener('click', function(){
                              area.style.display = "block";
                              area.value = content[i].innerText;
                              area.select();
                              document.execCommand('copy');   
                              area.style.display = "none";
                              
                              var t = this;
                              t.innerHTML = 'Cop<span style="color: red;">ied</span>';
                              setTimeout( function(){
                                t.innerHTML = "Copy"
                              }, 2000 );
                            });
                          }
                          
                          })();
                          hr { margin: 15px 0; border: none; }
                          <span class="js-content">1111</span>
                          <button class="js-copy">Copy</button>
                          <hr>
                          <span class="js-content">2222</span>
                          <button class="js-copy">Copy</button>
                          <hr>
                          <span class="js-content">3333</span>
                          <button class="js-copy">Copy</button>

                          【讨论】:

                            【解决方案22】:

                            我刚刚在做,我只是想知道是否有比我更好的方法,但是没有。

                            您可以使用我的代码,它会复制文本并显示工具提示。

                            头部

                            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
                            <link href="https://cdn.jsdelivr.net/npm/remixicon@2.2.0/fonts/remixicon.css" rel="stylesheet">
                            <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
                            <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
                            

                            身体

                            <div class="alert alert-primary alert-dismissible mb-0 py-1" role="alert" id="liveAlert">
                                <div class="container d-flex justify-content-between">
                                  <button type="button" class=" btn align-self-center ms-4 copytext" data-bs-toggle="tooltip" data-bs-placement="top" title=""><strong>Good news!</strong>  You just got 10% off, use your coupon <span class="fw-bold bg-secondary text-white px-2 maintext">store10off</span>. <i class="ri-file-copy-line"></i></button>
                                  <button type="button" class="btn align-self-center" data-bs-dismiss="alert" aria-label="Close"><strong class="fw-bold fs-4"><i class="ri-close-fill"></i></strong></button>
                                </div>
                                </div>
                            

                            功能

                            <script>
                                $('.copytext').click(function(){
                                    var thistooltip = $(this);
                                    var thistext = $(this).children('.maintext').text();
                                    navigator.clipboard.writeText(thistext);
                                    $(this).attr('title','copied');
                                    setTimeout(function(){$(thistooltip).tooltip("toggle");}, 800);
                                });
                            </script>
                            

                            【讨论】:

                              【解决方案23】:

                              非常简单。你一定是在搜索 js navigator.clipboard.writeText("thistext");
                              这将简单地复制文本“thistext”。现在让它在点击时工作,使用 jquery onclick 函数并将值(你想要复制的文本)存储在一个字符串中(如果你需要,那么你也可以使用 DOM 来从页面中获取一个值)和使用这行副本,而不是“thistext”,传递变量!

                              【讨论】:

                                【解决方案24】:
                                 document.getElementById('markup-copy').addEventListener('click', function() {
                                               var txt = "Your text Here";
                                                    $("<textarea/>").appendTo("body").val(txt).select().each(function () {
                                                    document.execCommand('copy');
                                                }).remove();
                                            });
                                

                                【讨论】:

                                  【解决方案25】:

                                  两者都会像魅力一样发挥作用:),

                                  JAVASCRIPT:

                                  function CopyToClipboard(containerid) {
                                  if (document.selection) { 
                                      var range = document.body.createTextRange();
                                      range.moveToElementText(document.getElementById(containerid));
                                      range.select().createTextRange();
                                      document.execCommand("copy"); 
                                  
                                  } else if (window.getSelection) {
                                      var range = document.createRange();
                                       range.selectNode(document.getElementById(containerid));
                                       window.getSelection().addRange(range);
                                       document.execCommand("copy");
                                       alert("text copied") 
                                  }}
                                  

                                  同样在html中,

                                  <button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>
                                  
                                  <div id="div1" >Text To Copy </div>
                                  
                                  <textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>
                                  

                                  查询: https://paulund.co.uk/jquery-copy-clipboard

                                  【讨论】:

                                    【解决方案26】:

                                    您可以使用导航器简单地执行复制到剪贴板。

                                    navigator.clipboard.writeText("Your text").
                                    

                                    【讨论】:

                                    • 这与this other answer 中的解决方案相同。 在回答已有答案的旧问题时,请确保提供新颖的解决方案或比现有答案更好的解释。
                                    猜你喜欢
                                    • 2021-12-10
                                    • 1970-01-01
                                    • 2011-06-21
                                    • 2010-09-23
                                    • 1970-01-01
                                    • 2020-10-18
                                    • 1970-01-01
                                    相关资源
                                    最近更新 更多