如何将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,它必须被粘贴。


当前回答

这里是HTML代码

    <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代码:

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

其他回答

没有flash或任何其他要求的更好方法是clipboard.js。你所需要做的就是在任何按钮上添加data-clipboard-target="#toCopyElement",初始化它new Clipboard('.btn');它会将id为toCopyElement的DOM内容复制到剪贴板。这是一个片段,通过链接复制您的问题中提供的文本。

虽然有一个限制是它不能在safari上运行,但它可以在所有其他浏览器上运行,包括移动浏览器,因为它不使用flash

$(函数(){ 新剪贴板(“.copy-text”); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> < script src = " https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js " > < /脚本> <p id="content">Lorem Ipsum只是印刷排版行业的假文本。自16世纪以来,Lorem Ipsum一直是行业标准的虚拟文本 <a class="copy- Text " data-clipboard-target="#content" href="#">copy Text</a>

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

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

你可以使用这个库轻松实现复制目标!

https://clipboardjs.com/

将文本复制到剪贴板应该不难。它不需要 数十个配置步骤或数百kb的加载。但是大部分 总之,它不应该依赖于Flash或任何膨胀的框架。 这就是clipboard.js存在的原因。

or

https://github.com/zeroclipboard/zeroclipboard

http://zeroclipboard.org/

ZeroClipboard库提供了一种简单的方法来将文本复制到 剪贴板使用一个不可见的Adobe Flash电影和JavaScript 接口。

这里是HTML代码

    <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代码:

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