如何将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,它必须被粘贴。


当前回答

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

其他回答

2022年6月

更新:现在正确的方法是使用剪贴板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')
    }
  )
})

就是这样。

如果你想看看在Clipboard 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;" />

更新2020:此解决方案使用execCommand。虽然这个功能在写这篇文章的时候还不错,但现在被认为已经过时了。它仍然可以在许多浏览器上工作,但不鼓励使用它,因为支持可能会被放弃。

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

例如,这个函数将把传递的元素的内容复制到剪贴板中(在PointZeroTwo的注释中更新了建议):

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

它是这样工作的:

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

注意元素的内部文本可以包含空格。因此,如果你想使用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" />

主要的问题是,目前并不是所有的浏览器都支持这个功能,但你可以在主要的浏览器上使用它:

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); } <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" />

注意,我们传递的是没有# now的id。

正如madzohan在下面的评论中报告的那样,在某些情况下,64位版本的谷歌Chrome浏览器存在一些奇怪的问题(在本地运行文件)。使用上面的非jquery解决方案似乎可以解决这个问题。

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

正如PointZeroTwo在评论中指出的那样,可以对代码进行改进,使其返回成功/失败结果。您可以在这个jsFiddle上看到一个演示。


更新:副本保持文本格式

正如一个用户在StackOverflow的西班牙版本中指出的那样,如果你想字面上复制一个元素的内容,上面列出的解决方案非常有效,但是如果你想用格式粘贴复制的文本,它们就不那么有效了(因为它被复制到输入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>

大多数建议的答案都会创建一个额外的临时隐藏输入元素。因为现在大多数浏览器都支持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>

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

文本复制是在文本输入,如:< input type="text" id="copyText" name="copyText">和,在按钮点击上面的文本应该被复制到剪贴板,所以按钮是像:<button type="submit" id="copy_button" data-clipboard-target='copyText'>复制</button>你的脚本应该像:

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

</script>

CDN文件

(zeroclipboard.swf): (zeroclipboard.js):

注意:ZeroClipboard.swf和ZeroClipboard.js”文件应该和你使用这个功能的文件在同一个文件夹中,或者你必须包括像我们包括<script src=""></script>在我们的页面上。