点击按钮复制到剪贴板使用jQuery [英] Click button copy to clipboard using jQuery

查看:177
本文介绍了点击按钮复制到剪贴板使用jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 < p class =content> Lorem Ipsum仅仅是印刷和排版行业的虚拟文本。自从1500年代以来,Lorem Ipsum一直是行业的标准虚拟文本< / p> 

< a class =copy-text> copy文字< / a>

点击复制文字后,按 Ctrl +

>

截至2016年,您现在可以在大多数浏览器中将文本复制到剪贴板,因为大多数浏览器都能够使用以编程方式将选定的文本复制到剪贴板,



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



下面是一个代码示例:



  document.getElementById(copyButton)addEventListener(click,function(){copyToClipboard(document.getElementById(copyTarget));}); function copyToClipboard(elem){//创建隐藏的文本元素(如果它不存在)var targetId =_hiddenCopyText_; var isInput = elem.tagName ===INPUT|| elem.tagName ===TEXTAREA; var origSelectionStart,origSelectionEnd; if(isInput){//只需使用原始源元素进行选择,并复制target = elem; origSelectionStart = elem.selectionStart; origSelectionEnd = elem.selectionEnd; } else {//必须使用临时表单元素进行选择和复制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; } //选择内容var currentFocus = document.activeElement; target.focus(); target.setSelectionRange(0,target.value.length); //复制选择var succeed; try {succeed = document.execCommand(copy); } catch(e){succeed = false; } // restore current focus if(currentFocus&& typeof currentFocus.focus ===function){currentFocus.focus(); } if(isInput){//恢复之前的选择elem.setSelectionRange(origSelectionStart,origSelectionEnd); } else {//清除临时内容target.textContent =; } return succeed;}  

  input {width:400px;}  

 < input type =textid =copyTarget value =Text to Copy> < button id =copyButton>复制< / button>< br>< br>< input type =textplaceholder =点击这里按Ctrl-V查看剪贴板内容 code> 






高级演示: https://jsfiddle.net/jfriend00/v9g1x0o6/



此外,您还可以通过 clipboard.js 获得预先构建的库。 / p>




回答的旧历史部分



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



如前所述, ZeroClipboard 是一组流行的代码,用于管理Flash对象以执行复制。我使用它。如果浏览设备(排除手机或平板电脑)上安装了Flash,则会正常工作。






解决方法是将剪贴板绑定文本放入输入字段,将焦点移动到该字段,并建议用户按 Ctrl + C 复制文本。



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







$ b b

这些问题要求使用Flash的现代替代方案已经收到许多问题upvote,没有解决方案的答案(可能因为没有解决方案):








Internet Explorer和Firefox过去有非标准API用于访问剪贴板,但是更现代的版本不赞成使用这些方法(可能出于安全原因)。






有一个突发标准努力试图提出一个安全的方式来解决最常见的剪贴板问题(可能需要一个特定的用户操作,如Flash解决方案要求) ,它似乎可能在最新版本的Firefox和Chrome中部分实现,但我还没有确认。


How do I copy the text inside a div to the clipboard? I have a div and need to add a link which will add the text to the clipboard. Is there a solution for this?

<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>

After I click copy text, then I press Ctrl + V, it must be pasted.

解决方案

Edit as of 2016

As of 2016, you can now copy text to the clipboard in most browsers because most browsers have the ability to programmatically copy a selection of text to the clipboard using document.execCommand("copy") that works off a selection.

As with some other actions in a browser (like opening a new window), the copy to clipboard can only be done via a specific user action (like a mouse click). For example, it cannot be done via a timer.

Here's a code example:

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">


Here's a little more advanced demo: https://jsfiddle.net/jfriend00/v9g1x0o6/

And, you can also get a pre-built library that does this for you with clipboard.js.


Old, historical part of answer

Directly copying to the clipboard via JavaScript is not permitted by any modern browser for security reasons. The most common workaround is to use a Flash capability for copying to the clipboard that can only be triggered by a direct user click.

As mentioned already, ZeroClipboard is a popular set of code for managing the Flash object to do the copy. I've used it. If Flash is installed on the browsing device (which rules out mobile or tablet), it works.


The next most common work-around is to just place the clipboard-bound text into an input field, move the focus to that field and advise the user to press Ctrl + C to copy the text.

Other discussions of the issue and possible work-arounds can be found in these prior Stack Overflow posts:


These questions asking for a modern alternative to using Flash have received lots of question upvotes and no answers with a solution (probably because none exist):


Internet Explorer and Firefox used to have non-standard APIs for accessing the clipboard, but their more modern versions have deprecated those methods (probably for security reasons).


There is a nascent standards effort to try to come up with a "safe" way to solve the most common clipboard problems (probably requiring a specific user action like the Flash solution requires), and it looks like it may be partially implemented in the latest versions of Firefox and Chrome, but I haven't confirmed that yet.

这篇关于点击按钮复制到剪贴板使用jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆