Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

jquery - 单击按钮使用jQuery复制到剪贴板(Click button copy to clipboard using jQuery)

How do I copy the text inside a div to the clipboard?

(如何将div中的文本复制到剪贴板?)

I have a div and need to add a link which will add the text to the clipboard.

(我有一个div,需要添加一个链接,该链接会将文本添加到剪贴板。)

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.

(单击复制文本后,然后按Ctrl + V ,必须将其粘贴。)

  ask by Dishan TD translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is another non-Flash way (apart from the Clipboard API mentioned in jfriend00's answer ).

(还有另一种非Flash方式(除了jfriend00的答案中提到的Clipboard API )。)

You need to select the text and then execute the command copy to copy to the clipboard whatever text is currently selected on the page.

(您需要选择文本,然后执行命令copy以将页面上当前选择的任何文本复制到剪贴板。)

For example, this function will copy the content of the passed element into the clipboard (updated with suggestion in the comments from PointZeroTwo ):

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

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

This is how it works:

(它是这样工作的:)

  1. Creates a temporary hidden text field.

    (创建一个临时的隐藏文本字段。)

  2. Copies the content of the element to that text field.

    (将元素的内容复制到该文本字段。)

  3. Selects the content of the text field.

    (选择文本字段的内容。)

  4. Executes the command copy like: document.execCommand("copy") .

    (执行命令副本,例如: document.execCommand("copy") 。)

  5. Removes the temporary text field.

    (删除临时文本字段。)

You can see a quick demo here:

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

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

The main issue is that not all browsers support this feature at the moment, but you can use it on the main ones from:

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

  • Chrome 43

    (镀铬43)

  • Internet Explorer 10

    (Internet Explorer 10)

  • Firefox 41

    (Firefox 41)

  • Safari 10

    (Safari 10)


Update 1: This can be achieved also with a pure JavaScript solution (no jQuery):

(更新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" /> 

Notice that we pass the id without the # now.

(请注意,我们传递的ID现在没有#号。)

As madzohan reported in the comments below, there is some strange issue with the 64-bit version of Google Chrome in some cases (running the file locally).

(正如madzohan在以下评论中所报告的那样,在某些情况下(本地运行文件),64位版本的Google Chrome浏览器存在一些奇怪的问题。)

This issue seems to be fixed with the non-jQuery solution above.

(上面的非jQuery解决方案似乎已解决了该问题。)

Madzohan tried in Safari and the solution worked but using document.execCommand('SelectAll') instead of using .select() (as specified in the chat and in the comments below).

(Madzohan在Safari中进行了尝试,该解决方案有效,但使用了document.execCommand('SelectAll')而不是.select() (如聊天室和以下注释中所指定)。)

As PointZeroTwo points out in the comments , the code could be improved so it would return a success/failure result.

(正如PointZeroTwo在注释中指出的那样,可以改进代码,以便返回成功/失败结果。)

You can see a demo on this jsFiddle .

(您可以在此jsFiddle上看到一个演示。)


UPDATE: COPY KEEPING THE TEXT FORMAT (更新:保留文本格式)

As a user pointed out in the Spanish version of StackOverflow , the solutions listed above work perfectly if you want to copy the content of an element literally, but they don't work that great if you want to paste the copied text with format (as it is copied into a input type="text" , the format is "lost").

(正如用户在西班牙语版本的StackOverflow中指出的那样,上面列出的解决方案如果您想按字面意义复制元素的内容,则可以完美地工作,但是,如果您想将复制的文本粘贴为格式(如将其复制到input type="text" ,格式为“ lost”)。)

A solution for that would be to copy into a content editable div and then copy it using the execCommand in a similar way.

(一种解决方案是将其复制到内容可编辑的div ,然后以类似方式使用execCommand复制它。)

Here there is an example - click on the copy button and then paste into the content editable box below:

(这里有一个例子-单击复制按钮,然后粘贴到下面的内容可编辑框中:)

 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> 

And in jQuery, it would be like this:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...