单击按钮复制到剪贴板 [英] Click button copy to clipboard

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

问题描述

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

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>

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

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

推荐答案

Edit as of 2016

自 2016 年起,您现在可以在大多数浏览器中将文本复制到剪贴板,因为大多数浏览器都能够使用 document.execCommand("copy") 以编程方式将所选文本复制到剪贴板这适用于选择.

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.

这是一个代码示例:

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/

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

而且,您还可以使用 clipboard.js.

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

答案的旧的历史部分

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

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.

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

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.

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

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.

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

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

如何复制使用 jQuery 将文本发送到客户端的剪贴板?

怎么可以你在没有 Flash 的情况下复制到剪贴板?

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

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

复制到剪贴板,无需 Flash

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

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

有一个新生标准努力试图提出一个安全的" 解决最常见的剪贴板问题的方法(可能需要像 Flash 解决方案那样需要特定的用户操作),看起来它可能在最新版本的 Firefox 和 Chrome 中部分实现,但我还没有确认.

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.

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

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