使用jQuery单击按钮复制到剪贴板

Dis*_* TD 401 html css jquery

如何将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>
Run Code Online (Sandbox Code Playgroud)

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

Alv*_*oro 587

还有另一种非Flash方式(除了jfriend00的答案中提到的Clipboard API).您需要选择文本然后执行命令以将任何当前在页面上选中的文本复制到剪贴板.copy

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

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

这是它的工作原理:

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

你可以在这里看到一个快速演示:

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}
Run Code Online (Sandbox Code Playgroud)
<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" />
Run Code Online (Sandbox Code Playgroud)

主要问题是目前并非所有浏览器都支持此功能,但您可以在以下主要功能上使用它:

  • Chrome 43
  • Internet Explorer 10
  • Firefox 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);

}
Run Code Online (Sandbox Code Playgroud)
<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" />
Run Code Online (Sandbox Code Playgroud)

请注意,我们在没有#now的情况下传递了id.

正如madzohan在下面的评论中所述,在某些情况下,64位版本的谷歌浏览器存在一些奇怪的问题(在本地运行该文件).上面的非jQuery解决方案似乎解决了这个问题.

Madzohan尝试在Safari中使用解决方案,但使用document.execCommand('SelectAll')而不是使用.select()(如聊天和下面的评论中所述).

正如PointZeroTwo在评论中指出的那样,代码可以得到改进,因此它会返回成功/失败结果.你可以在这个jsFiddle上看到一个演示.


更新:复制保留文本格式

正如用户在西班牙语版本的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);
}
Run Code Online (Sandbox Code Playgroud)
#target {
  width:400px;
  height:100px;
  border:1px solid #ccc;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

在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();
}
Run Code Online (Sandbox Code Playgroud)
#target {
  width:400px;
  height:100px;
  border:1px solid #ccc;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • 原始的jQuery实现无法保留换行符,因为它使用的是INPUT元素.使用TEXTAREA代替解决这个问题. (7认同)
  • 奇怪......这里有效,但我无法在本地工作0o jquery-1.11.3 Chrome 43.0.2357.130(64位) (5认同)
  • 这对我来说不起作用,直到我通过添加以下行确保在页面上看到aux:`aux.style.position ="fixed";``aux.style.top = 0;``appendChild上方`打电话. (3认同)
  • @madzohan好的,我能够重现该问题。这很奇怪,因为我只能在64位Chrome的本地(file://)上复制它。我还找到了一个适用于我的快速解决方案:使用纯JavaScript而不是jQuery。我将用该代码更新答案。请检查它,让我知道它是否适合您。 (2认同)

jfr*_*d00 449

编辑截至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;
}
Run Code Online (Sandbox Code Playgroud)
input {
  width: 400px;
}
Run Code Online (Sandbox Code Playgroud)
<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">
Run Code Online (Sandbox Code Playgroud)


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

而且,您还可以使用clipboard.js获得一个预先构建的库,为您完成此任务.


回答的老,历史部分

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

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


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

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


这些问题要求使用Flash的现代替代方案已经收到了许多问题upvotes并且没有解决方案的答案(可能因为不存在):


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


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

  • 仅供参考[每套Safari发行说明](https://developer.apple.com/library/prerelease/content/releasenotes/General/WhatsNewInSafari/Articles/Safari_10_0.html),Safari 10现在支持` document.execCommand("copy")`所以这段代码现在可以在Safari 10中使用了. (2认同)

a c*_*der 35

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>
Run Code Online (Sandbox Code Playgroud)

clipboard.js也在GitHub上.

2016年1月15日编辑:今天编辑最佳答案是在2015年8月发布的答案中引用相同的API.之前的文本指示用户使用ZeroClipboard.只是想明确我没有从jfriend00的答案中扯出这个,而是反过来.


tha*_*ker 20

从 2021 年开始,您应该使用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')
});
Run Code Online (Sandbox Code Playgroud)

这是有关与剪贴板交互的更多信息

  • 使用 jquery,您可以将以下代码添加到任何 html 元素:`onclick="navigator.clipboard.writeText($(this).text());"` (6认同)

Nad*_*dav 18

简约是最终的成熟.
如果您不希望要显示的文本是可见的:

jQuery:

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

HTML:

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

  • 这里有太多复杂的答案,因此感谢您。 (4认同)

小智 10

换行(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());
Run Code Online (Sandbox Code Playgroud)


小智 9

<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();
}
Run Code Online (Sandbox Code Playgroud)


Amg*_*gad 7

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

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

$(function(){
  new Clipboard('.copy-text');
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


hol*_*321 6

jQuery 简单的解决方案。

应该由用户的点击触发。

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


kei*_*ani 6

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

这是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>
Run Code Online (Sandbox Code Playgroud)

然后对于此html,我们必须使用此JQuery代码

function copyToClipboard(element) {
    $(element).select();
    document.execCommand("copy");
}
Run Code Online (Sandbox Code Playgroud)

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


Ujj*_*pta 5

<!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>
Run Code Online (Sandbox Code Playgroud)


Mar*_*ter 5

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


Dia*_*ani 5

<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>
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

674399 次

最近记录:

6 年 前