如何将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>

在我点击复制文本,然后我按Ctrl + V,它必须被粘贴。


当前回答

输入字段没有display: none,这一点非常重要。浏览器不会选择文本,因此不会被复制。使用不透明度:0,宽度为0px来解决这个问题。

其他回答

HTML:

// you need bootstrap(js && css) and JQuery(js)
<span class="text-copy" value="your-text">text</span>

CSS:

.text-copy {
  cursor: pointer;
  color: #0d6efd;
  text-decoration: underline;
}
.text-copy:hover {
  color: #1b6be4;
}

JS(使用JQuery):

$(document).ready(function() {
  var elements = $('.copy-text');
  for(let i = 0; i < elements.length; i++) {
    const element = $(elements[i]);
    element.attr('data-toggle', 'tooltip')
           .attr('data-placement', 'top')
           .attr('title', `Tab to copy "${element.attr('value')}"`);
  }
  $('[data-toggle="tooltip"]').tooltip();
  $('.text-copy').click(function() {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($(this).attr('value')).select();
    document.execCommand("copy");
    $temp.remove();
  });
});

$(document).ready(async function() { var elements = $('.text-copy'); for(let i = 0; i<elements.length; i++) { const element = $(elements[i]); element.attr('data-toggle', 'tooltip') .attr('data-placement', 'top') .attr('title', `Tab to copy "${element.attr('value')}"`); } $('[data-toggle="tooltip"]').tooltip(); $('.text-copy').click(function() { var $temp = $("<input>"); $("body").append($temp); $temp.val($(this).attr('value')).select(); document.execCommand("copy"); $temp.remove(); }); }); body { display: grid; justify-content: center; } .text-copy { cursor: pointer; color: #0d6efd; text-decoration: underline; } .text-copy:hover { color: #1b6be4; } <html> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"></script> </head> <body> <h2 class="text-copy" value="your copy text">your text</h2> <br> <h4>paste here</h4> <input type="text"> </body> </html>

纯JS,没有内联onclick,配对类“内容-复制按钮”。如果你有很多元素,会更舒服)

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

旧的浏览器支持:

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

2022年6月

更新:现在正确的方法是使用剪贴板API。

例如:

// get the text from the DOM Element: 
const textToCopy = document.querySelector('.content').innerText

// when someone clicks on the <a class="copy-text"> element 
// (which should be a <button>), execute the copy command:
document.querySelector('.copy-text').addEventListener('click' , ()=> {
  navigator.clipboard.writeText(textToCopy).then(
    function() {
      /* clipboard successfully set */
      window.alert('Success! The text was copied to your clipboard') 
    }, 
    function() {
      /* clipboard write failed */
      window.alert('Opps! Your browser does not support the Clipboard API')
    }
  )
})

就是这样。

如果你想看看在Clipboard API引入之前的解决方案(现在不是一个好的实践):

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

这是一个优雅的Javascript解决方案

<input type="text" value="Foo Bar" id="your_input">
<button onclick="copy()">Copy text</button>

<script type="application/javascript">
function copy() {
  var copiedtext = document.getElementById("your_input");
  copiedtext.select();
  copiedtext.setSelectionRange(0, 99999); //for mobile devices
  navigator.clipboard.writeText(copiedtext.value);
  alert("You just copied " + copiedtext.value);
}
</script>

您可以使用此代码通过单击剪贴板中的按钮复制页中的输入值

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

然后对于这个html,我们必须使用这个JQuery代码

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

这是这个问题最简单的解