Klik op knop kopiëren naar klembord met jQuery

Hoe kopieer ik de tekst in een div naar het klembord? Ik heb een div en moet een link toevoegen die de tekst aan het klembord zal toevoegen. Is hier een oplossing voor?

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

Nadat ik op tekst kopiëren heb geklikt, druk ik op Ctrl + V, het moet worden geplakt.


Antwoord 1, autoriteit 100%

Bewerken vanaf 2016

Vanaf 2016 kunt u nu in de meeste browsers tekst naar het klembord kopiëren, omdat de meeste browsers de mogelijkheid hebben om een ​​selectie van tekst programmatisch naar het klembord te kopiëren met behulp van document.execCommand("copy") dat werkt uit een selectie.

Net als bij sommige andere acties in een browser (zoals het openen van een nieuw venster), kan het kopiëren naar het klembord alleen worden gedaan via een specifieke gebruikersactie (zoals een muisklik). Het kan bijvoorbeeld niet via een timer.

Hier is een codevoorbeeld:

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

Antwoord 2, autoriteit 91%

Update 2020: deze oplossing gebruikt execCommand. Hoewel die functie op het moment van schrijven van dit antwoord prima was, is het nu als verouderd beschouwd. Het zal nog steeds werken in veel browsers, maar het gebruik ervan wordt afgeraden omdat de ondersteuning kan komen te vervallen.

Er is een andere niet-Flash manier (afgezien van de Clipboard API genoemd in antwoord van jfriend00). U moet de tekst selecteren en vervolgens het commando copy om de tekst die momenteel op de pagina is geselecteerd naar het klembord te kopiëren.

Deze functie kopieert bijvoorbeeld de inhoud van het doorgegeven element naar het klembord (bijgewerkt met suggestie in de opmerkingen van PointZeroTwo):

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

Zo werkt het:

  1. Maakt een tijdelijk verborgen tekstveld.
  2. Kopieert de inhoud van het element naar dat tekstveld.
  3. Selecteert de inhoud van het tekstveld.
  4. Voert het commando copy uit zoals: document.execCommand("copy").
  5. Verwijdert het tijdelijke tekstveld.

LET OP dat de binnentekst van het element witruimte kan bevatten. Dus als je if wilt gebruiken, bijvoorbeeld voor wachtwoorden, kun je de tekst inkorten door $(element).text().trim() in de bovenstaande code te gebruiken.

Je kunt hier een korte demo bekijken:

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

Antwoord 3, autoriteit 7%

clipboard.js is een leuk hulpprogramma waarmee tekst of HTML-gegevens kunnen worden gekopieerd naar het klembord zonder gebruik van Flash. Het is heel gemakkelijk te gebruiken; voeg gewoon de .js toe en gebruik zoiets als dit:

<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 staat ook op GitHub.

Bewerken op 15 januari 2016: het topantwoord was bewerkt vandaag om naar dezelfde API te verwijzen in mijn antwoord van augustus 2015. De vorige tekst gaf gebruikers de instructie om ZeroClipboard te gebruiken. Ik wil gewoon duidelijk zijn dat ik dit niet uit het antwoord van jfriend00 heb gehaald, eerder andersom.


Antwoord 4, autoriteit 7%

Eenvoud is de ultieme verfijning.
Als u niet wilt dat de te kopiëren tekst zichtbaar is:

jQuery:

$('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;" />

Antwoord 5, autoriteit 3%

Met regelonderbrekingen (uitbreiding van het antwoord van 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());

Antwoord 6, autoriteit 3%

Vanaf 2021 moet u de Clipboard Api gebruiken .

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')
});

Hier vindt u meer informatie over interactie met het klembord


Antwoord 7, autoriteit 2%

Een nog betere aanpak zonder flash of andere vereisten is clipboard.js. Het enige wat u hoeft te doen is data-clipboard-target="#toCopyElement" toe te voegen aan een knop, deze te initialiseren new Clipboard('.btn'); en het zal kopiëren de inhoud van DOM met id toCopyElement naar klembord. Dit is een fragment dat de tekst in uw vraag kopieert via een link.

Een beperking is echter dat het niet werkt op safari, maar het werkt op alle andere browsers, inclusief mobiele browsers, omdat het geen flash gebruikt

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

Antwoord 8, autoriteit 2%

<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();
}

Antwoord 9

U kunt deze code gebruiken om de invoerwaarde op de pagina in het klembord te kopiëren door op een knop te klikken

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

Voor deze html moeten we deze JQuery-code gebruiken

function copyToClipboard(element) {
    $(element).select();
    document.execCommand("copy");
}

Dit is de eenvoudigste oplossing voor deze vraag


Antwoord 10

jQuery eenvoudige oplossing.

Moet worden geactiveerd door de klik van de gebruiker.

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

Antwoord 11

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

Antwoord 12

Het is erg belangrijk dat het invoerveld geen display: none heeft. De browser selecteert de tekst niet en wordt daarom niet gekopieerd. Gebruik opacity: 0 met een breedte van 0px om het probleem op te lossen.


Antwoord 13

Het is de eenvoudigste methode om de inhoud te kopiëren

 <div id="content"> Lorepm ispum </div>
 <button class="copy" title="content">Copy Sorce</button>
function SelectContent(element) {
                        var doc = document
                            , text = doc.getElementById(element)
                            , range, selection
                        ;    
                        if (doc.body.createTextRange) {
                            range = document.body.createTextRange();
                            range.moveToElementText(text);
                            range.select();
                        } else if (window.getSelection) {
                            selection = window.getSelection();        
                            range = document.createRange();
                            range.selectNodeContents(text);
                            selection.removeAllRanges();
                            selection.addRange(range);
                        }
                         document.execCommand('Copy');
                    }
                    $(".copy").click(function(){
                         SelectContent( $(this).attr('title'));
                    });

Antwoord 14

De meeste van de voorgestelde antwoorden creëren een extra tijdelijk verborgen invoerelement(en). Omdat de meeste browsers tegenwoordig div-inhoudsbewerking ondersteunen, stel ik een oplossing voor die geen verborgen element(en) maakt, tekstopmaak behoudt en pure JavaScript- of jQuery-bibliotheek gebruikt.

Hier is een minimalistische skeletimplementatie met de minste regels codes die ik kon bedenken:

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

Antwoord 15

De te kopiëren tekst is in tekstinvoer, zoals: <input type="text" id="copyText" name="copyText"> en, als op de knop hierboven wordt geklikt, moet de tekst worden weergegeven gekopieerd naar het klembord, dus de knop is als:<button type="submit" id="copy_button" data-clipboard-target='copyText'>Copy</button> Je script zou moeten zijn als :

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

Voor CDN-bestanden

opmerking: ZeroClipboard.swf en ZeroClipboard.js“-bestand moeten zich in dezelfde map bevinden als uw bestand dat deze functionaliteit gebruikt, OF je moet opnemen zoals we <script src=""></script> op onze pagina’s opnemen.


Antwoord 16

je kunt dit lib gewoon gebruiken om het kopieerdoel gemakkelijk te realiseren!

https://clipboardjs.com/

Het kopiëren van tekst naar het klembord zou niet moeilijk moeten zijn. Het zou niet nodig moeten zijn
tientallen stappen om te configureren of honderden KB’s om te laden. Maar de meeste van
het zou niet afhankelijk moeten zijn van Flash of een opgeblazen framework.

Daarom bestaat clipboard.js.

of

https://github.com/zeroclipboard/zeroclipboard

http://zeroclipboard.org/

De ZeroClipboard-bibliotheek biedt een gemakkelijke manier om tekst naar de
klembord met een onzichtbare Adobe Flash-film en een JavaScript
interface.


Antwoord 17

Clipboard-polyfill bibliotheek is een polyfill voor het moderne op Promise gebaseerde asynchrone klembord API.

installeren in CLI:

npm install clipboard-polyfill 

importeren als klembord in JS-bestand

window.clipboard = require('clipboard-polyfill');

voorbeeld

Ik gebruik het in een bundel met require("babel-polyfill"); en heb het getest op chrome 67. Allemaal goed voor productie.


Antwoord 18

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

Antwoord 19

html-code hier

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

Antwoord 20

u kunt een afzonderlijke tekst kopiëren behalve de tekst van een HTML-element.

        var copyToClipboard = function (text) {
            var $txt = $('<textarea />');
            $txt.val(text)
                .css({ width: "1px", height: "1px" })
                .appendTo('body');
            $txt.select();
            if (document.execCommand('copy')) {
                $txt.remove();
            }
        };

Antwoord 21

Pure JS, zonder inline onclick, voor gepaarde klassen “inhoud – kopieerknop”. Zou comfortabeler zijn als je veel elementen hebt)

(function(){
/* Creating textarea only once, but not each time */
let area = document.createElement('textarea');
document.body.appendChild( area );
area.style.display = "none";
let content = document.querySelectorAll('.js-content');
let copy    = document.querySelectorAll('.js-copy');
for( let i = 0; i < copy.length; i++ ){
  copy[i].addEventListener('click', function(){
    area.style.display = "block";
    /* because the classes are paired, we can use the [i] index from the clicked button,
    to get the required text block */
    area.value = content[i].innerText;
    area.select();
    document.execCommand('copy');   
    area.style.display = "none";
    /* decorative part */
    this.innerHTML = 'Cop<span style="color: red;">ied</span>';
    /* arrow function doesn't modify 'this', here it's still the clicked button */
    setTimeout( () => this.innerHTML = "Copy", 2000 );
  });
}
})();
hr { margin: 15px 0; border: none; }
<span class="js-content">1111</span>
<button class="js-copy">Copy</button>
<hr>
<span class="js-content">2222</span>
<button class="js-copy">Copy</button>
<hr>
<span class="js-content">3333</span>
<button class="js-copy">Copy</button>

Antwoord 22

Beide werken als een tierelier :),

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

Ook 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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

three + four =

Other episodes