如何将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>
Run Code Online (Sandbox Code Playgroud)
单击复制文本后,我按Ctrl+ V,必须粘贴.
当前代码附加一个按钮,可以快速选择<pre>标记中的某些代码.我想要添加的是能够将该内容复制到剪贴板并将按钮文本更改为"复制".
如何通过修改下面的当前工作代码来实现它?我不介意使用clipboard.js,jQuery位或者只是原生的JS支持,因为它是从Chrome 43开始引入的.我只是不知道如何继续添加我需要的东西.
function selectPre(e) {
if (window.getSelection) {
var s = window.getSelection();
if (s.setBaseAndExtent) {
s.setBaseAndExtent(e, 0, e, e.innerText.length - 1);
}
else {
var r = document.createRange();
r.setStart(e.firstChild, 0);
r.setEnd(e.lastChild, e.lastChild.textContent.length);
s.removeAllRanges();
s.addRange(r);
}
}
else if (document.getSelection) {
var s = document.getSelection();
var r = document.createRange();
r.selectNodeContents(e);
s.removeAllRanges();
s.addRange(r);
}
else if (document.selection) {
var r = document.body.createTextRange();
r.moveToElementText(e);
r.select();
}
}
var diff = document.getElementById('diff_table').getElementsByTagName('tr');
var difflen = diff.length;
for(i=0; i<difflen; i++) {
var …Run Code Online (Sandbox Code Playgroud) 不知道为什么今天对我这么困难,但由于某种原因我似乎无法将当前的URL复制到剪贴板.总的来说,我正在寻找一种方法来做到这一点,而无需创建一些隐藏的文本元素.
这是我到目前为止所尝试的:
var shareBtn = document.querySelector(".share-button");
shareBtn.addEventListener('click', function(event) {
var cpLink = window.location.href;
cpLink.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copy command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
event.preventDefault;
});
Run Code Online (Sandbox Code Playgroud)
当我尝试使用它时,.select()我得到了这个错误:
t.select is not a function
所以我不是100%确定最好的方法是什么.再次,不使用jQuery(或任何其他JS库)而不使用某种隐藏的文本字段.