Bagaimana cara menyalin teks di dalam sebuah div untuk clipboard? Saya memiliki div dan perlu untuk menambahkan link yang akan menambahkan teks ke clipboard. Apakah ada solusi untuk ini?
<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>
Setelah saya klik salin teks, kemudian saya tekan Pilih + V, maka harus disisipkan.
Ada lagi non-cara Flash (terlepas dari Clipboard API disebutkan dalam jfriend00's jawaban). Anda perlu memilih teks dan kemudian mengeksekusi perintah copy
untuk menyalin ke clipboard teks apapun yang sedang dipilih pada halaman.
Sebagai contoh, fungsi ini akan menyalin isi berlalu elemen ke clipboard (diperbarui dengan saran di komentar dari PointZeroTwo):
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
Ini adalah cara kerjanya:
Anda dapat melihat demo cepat berikut ini:
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" />
Masalah utama adalah bahwa tidak semua browser mendukung]5 fitur ini pada saat ini, tetapi anda dapat menggunakannya pada yang utama dari:
Update 1: hal Ini dapat dicapai juga dengan JavaScript murni solusi (tanpa 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" />
Perhatikan bahwa kita melewati id tanpa # sekarang.
Sebagai madzohan dilaporkan di komentar di bawah ini, ada beberapa masalah aneh dengan 64-bit versi Google Chrome di beberapa kasus (menjalankan file lokal). Masalah ini tampaknya akan tetap dengan non-jQuery solusi di atas.
Madzohan mencoba di Safari dan solusi bekerja tetapi menggunakan dokumen.execCommand('SelectAll')
alih-alih menggunakan .select()
(seperti yang ditentukan di chat dan di komentar di bawah ini).
Sebagai PointZeroTwo poin di komentar, kode ini bisa terus ditingkatkan sehingga akan kembali keberhasilan/kegagalan hasilnya. Anda dapat melihat demo di [ini jsFiddle][7].
Sebagai user mencontohkan dalam versi bahasa spanyol dari StackOverflow, solusi yang tercantum di atas bekerja dengan sempurna jika anda ingin menyalin isi dari sebuah elemen secara harfiah, tetapi mereka don't bekerja yang besar jika anda ingin menyisipkan teks disalin dengan format (seperti yang disalin ke dalam input type="text"
, format "hilang").
Solusi untuk itu akan salin ke dalam sebuah konten dapat diedit div
dan kemudian menyalinnya menggunakan execCommand
dengan cara yang sama. Berikut ini ada contoh - klik pada tombol copy dan kemudian paste ke dalam konten dapat diedit kotak di bawah ini:
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>
Dan di jQuery, itu akan menjadi seperti ini:
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>
Edit seperti 2016
Pada 2016, anda sekarang dapat menyalin teks ke clipboard di sebagian besar browser karena browser yang paling memiliki kemampuan untuk pemrograman menyalin teks ke clipboard menggunakan dokumen.execCommand("copy")
yang bekerja dari sebuah pilihan.
Seperti dengan beberapa tindakan lain dalam browser (seperti membuka jendela baru), copy ke clipboard hanya dapat dilakukan melalui pengguna tertentu tindakan (seperti klik mouse). Misalnya, hal ini tidak dapat dilakukan melalui timer.
Berikut ini's contoh kode:
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">
Berikut ini's sedikit lebih canggih demo:
Dan, anda juga bisa mendapatkan pra-dibangun perpustakaan yang melakukan ini untuk anda dengan clipboard.js.
Tua, sejarah bagian dari jawaban
Langsung menyalin ke clipboard melalui JavaScript tidak diizinkan oleh browser modern untuk alasan keamanan. Yang paling umum mengatasinya adalah dengan menggunakan Flash dan kemampuan untuk menyalin ke clipboard yang hanya dapat dipicu oleh pengguna langsung klik.
Seperti yang sudah disebutkan, ZeroClipboard adalah tempat sekumpulan kode untuk mengelola objek Flash untuk melakukan copy. I've digunakan. Jika Flash diinstal pada browsing perangkat (yang menandakan ponsel atau tablet), ia bekerja.
Berikutnya yang paling umum adalah dengan hanya menempatkan clipboard teks yang terikat ke sebuah field input, memindahkan fokus ke bidang tersebut dan menyarankan pengguna untuk tekan Pilih + C untuk menyalin teks.
Diskusi lain dari masalah ini dan mungkin pekerjaan-arounds dapat ditemukan di ini sebelum Stack Overflow posting:
https://stackoverflow.com/questions/400212/how-to-copy-to-the-clipboard-in-javascript
https://stackoverflow.com/questions/1539641/how-to-copy-text-to-the-clients-clipboard-using-jquery
Pertanyaan-pertanyaan ini meminta alternatif modern untuk menggunakan Flash telah menerima banyak pertanyaan upvotes dan tidak ada jawaban dengan solusi (mungkin karena tidak ada):
Internet Explorer dan Firefox yang digunakan untuk non-standar Api untuk mengakses clipboard, tetapi versi yang lebih modern telah usang metode tersebut (mungkin untuk alasan keamanan).
Ada baru lahir standar usaha untuk mencoba untuk datang dengan "aman" cara untuk memecahkan yang paling umum clipboard masalah (mungkin memerlukan pengguna tertentu tindakan seperti Flash membutuhkan solusi), dan itu tampak seperti itu mungkin sebagian diimplementasikan pada versi terbaru dari Firefox dan Chrome, tapi saya belum't menegaskan bahwa belum.
clipboard.js adalah sebuah utilitas yang memungkinkan menyalin teks atau HTML data ke clipboard tanpa menggunakan Flash. It's sangat mudah digunakan; hanya mencakup .js dan menggunakan sesuatu seperti ini:
<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>
Edit pada 15 Januari 2016: The atas jawaban adalah diedit hari ini untuk referensi yang sama API di jawaban saya posted in agustus 2015. Teks sebelumnya telah menginstruksikan pengguna untuk menggunakan ZeroClipboard. Hanya ingin menjadi jelas bahwa aku tidak't yank ini dari jfriend00's jawaban, bukan sebaliknya.
Kesederhanaan adalah kecanggihan yang tertinggi.
Jika anda don't ingin teks-to-be-coppied akan terlihat:
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;" />
Dengan Garis Istirahat (Extention Jawaban dari 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());
Bahkan pendekatan yang lebih baik tanpa flash atau persyaratan lain adalah clipboard.js. Semua yang perlu anda lakukan adalah menambahkan data-clipboard-target="#toCopyElement"pada setiap tombol, menginisialisasi
baru Clipboard('.btn');dan itu akan menyalin konten dari DOM dengan id
toCopyElement` ke clipboard. Ini adalah cuplikan yang menyalin teks yang disediakan dalam pertanyaan anda melalui link.
Salah satu keterbatasan meskipun adalah bahwa hal itu tidak bekerja pada safari, tetapi bekerja pada semua browser lain termasuk browser mobile seperti tidak menggunakan flash
$(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>
Anda dapat menggunakan kode ini untuk menyalin nilai masukan di halaman dalam Clipboard dengan mengklik tombol
Ini adalah 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>
Kemudian untuk html ini , kita harus menggunakan Kode JQuery
function copyToClipboard(element) {
$(element).select();
document.execCommand("copy");
}
Ini adalah solusi sederhana untuk pertanyaan ini
<!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>
<div class="form-group">
<label class="font-normal MyText">MyText to copy</label>
<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();
}
Ini adalah metode yang paling sederhana untuk menyalin isi
<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'));
});
It's sangat penting bahwa field input tidak memiliki display: none
. Browser tidak akan pilih teks dan oleh karena itu tidak akan disalin. Gunakan opacity: 0
dengan lebar 0px untuk memperbaiki masalah.
anda hanya dapat menggunakan lib ini mudah untuk mewujudkan copy gol!
Menyalin teks ke clipboard seharusnya't menjadi keras. Seharusnya't membutuhkan puluhan langkah-langkah untuk mengkonfigurasi atau ratusan KBs dengan beban. Tapi yang paling dari semua, seharusnya't tergantung pada Flash atau kembung framework.
Yang's mengapa clipboard.js ada.
atau
https://github.com/zeroclipboard/zeroclipboard
ZeroClipboard perpustakaan menyediakan cara yang mudah untuk menyalin teks ke clipboard menggunakan terlihat Adobe Flash movie dan JavaScript antarmuka.
Sebagian besar jawaban yang diusulkan buat sementara tambahan tersembunyi elemen input(s). Karena kebanyakan browser saat ini mendukung div mengedit konten, saya mengusulkan sebuah solusi yang tidak membuat elemen tersembunyi(s), melestarikan format teks dan menggunakan pure JavaScript atau jQuery library.
Berikut ini adalah minimalis kerangka implementasi menggunakan paling sedikit baris kode yang saya pikirkan:
//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>
Teks untuk menyalin teks input,seperti: <input type="text" id="copyText" name="copyText">
dan, pada tombol klik teks di atas harus mendapatkan disalin ke clipboard,sehingga tombol seperti:<button type="kirim" id="copy_button" data-clipboard-target='copyText'>Copy</tombol>
script Anda harus menjadi seperti:
<script language="JavaScript">
$(document).ready(function() {
var clip = new ZeroClipboard($("#copy_button"), {
moviePath: "ZeroClipboard.swf"
});
});
</script>
Untuk CDN file
catatan: ZeroClipboard.swf
dan ZeroClipboard.js
" file harus dalam folder yang sama sebagai file anda menggunakan fungsi ini, ATAU anda harus menyertakan seperti kita termasuk <script src=""></script>
di halaman kami.
Clipboard-polyfill perpustakaan adalah polyfill modern Janji berbasis asynchronous clipboard API.
menginstal pada CLI:
npm install clipboard-polyfill
impor sebagai clipboard di JS file
window.clipboard = require('clipboard-polyfill');
I'm menggunakannya di bundel dengan memerlukan("babel-polyfill");
dan diuji pada chrome 67. Semua baik untuk produksi.
html di sini
<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" />
KODE:JS
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);
}
anda dapat menyalin teks individu terlepas dari sebuah elemen HTML's teks.
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();
}
};
JS murni, tanpa inline onclick, untuk dipasangkan kelas "content - copy tombol". Akan lebih nyaman, jika anda memiliki banyak elemen)
(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>
Tua browser yang mendukung:
(function(){
var area = document.createElement('textarea');
document.body.appendChild( area );
area.style.display = "none";
var content = document.querySelectorAll('.js-content');
var copy = document.querySelectorAll('.js-copy');
for( var i = 0; i < copy.length; i++ ){
copyOnClick(i);
}
function copyOnClick(i){
copy[i].addEventListener('click', function(){
area.style.display = "block";
area.value = content[i].innerText;
area.select();
document.execCommand('copy');
area.style.display = "none";
var t = this;
t.innerHTML = 'Cop<span style="color: red;">ied</span>';
setTimeout( function(){
t.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>
Keduanya akan bekerja seperti pesona :),
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")
}}
Juga dalam 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>