Click button copy to clipboard using jQuery

2018-12-31 04:44发布

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.

标签: jquery html css
18条回答
荒废的爱情
2楼-- · 2018-12-31 05:28

you can just using this lib for easy realize the copy goal!

https://clipboardjs.com/

Copying text to the clipboard shouldn't be hard. It shouldn't require dozens of steps to configure or hundreds of KBs to load. But most of all, it shouldn't depend on Flash or any bloated framework.

That's why clipboard.js exists.

or

https://github.com/zeroclipboard/zeroclipboard

http://zeroclipboard.org/

The ZeroClipboard library provides an easy way to copy text to the clipboard using an invisible Adobe Flash movie and a JavaScript interface.

查看更多
泛滥B
3楼-- · 2018-12-31 05:29

clipboard.js is a nice utility that allows copying of text or HTML data to the clipboard without use of Flash. It's very easy to use; just include the .js and use something like this:

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

clipboard.js is also on GitHub.

Edit on Jan 15, 2016: The top answer was edited today to reference the same API in my answer posted in August 2015. The previous text was instructing users to use ZeroClipboard. Just want to be clear that I didn't yank this from jfriend00's answer, rather the other way around.

查看更多
几人难应
4楼-- · 2018-12-31 05:30

Most of the proposed answers create an extra temporary hidden input element(s). Because most browsers nowadays support div content edit, I propose a solution that does not create hidden element(s), preserve text formatting and use pure JavaScript or jQuery library.

Here is a minimalist skeleton implementation using the fewest lines of codes I could think of:

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

查看更多
还给你的自由
5楼-- · 2018-12-31 05:32

It's very important that the input field does not have display: none. The browser will not select the text and therefore will not be copied. Use opacity: 0 with a width of 0px to fix the problem.

查看更多
妖精总统
6楼-- · 2018-12-31 05:33

html code here

    <input id="result" style="width:300px"/>some example text
    <button onclick="copyToClipboard('result')">Copy P1</button>
    <input type="text" style="width:400px" placeholder="Paste here for test" />

JS CODE:

     function copyToClipboard(elementId) {

                      // Create a "hidden" input
                      var aux = document.createElement("input");

                      aux.setAttribute("value", document.getElementById(elementId).value);
                      // 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);
                    }
查看更多
墨雨无痕
7楼-- · 2018-12-31 05:33

Both will works like a charm :),

JAVASCRIPT:

function CopyToClipboard(containerid) {
if (document.selection) { 
    var range = document.body.createTextRange();
    range.moveToElementText(document.getElementById(containerid));
    range.select().createTextRange();
    document.execCommand("copy"); 

} else if (window.getSelection) {
    var range = document.createRange();
     range.selectNode(document.getElementById(containerid));
     window.getSelection().addRange(range);
     document.execCommand("copy");
     alert("text copied") 
}}

Also in html,

<button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>

<div id="div1" >Text To Copy </div>

<textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>

JQUERY: https://paulund.co.uk/jquery-copy-clipboard

查看更多
登录 后发表回答