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


当前回答

jQuery简单解决方案。

应由用户点击触发。

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

其他回答

js是一个很好的实用工具,它允许在不使用Flash的情况下将文本或HTML数据复制到剪贴板。它很容易使用;只需要包含.js并使用如下代码:

<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也在GitHub上。

2016年1月15日编辑:今天编辑了顶部的答案,引用了我在2015年8月发布的答案中的相同API。前面的文本指示用户使用ZeroClipboard。只是想澄清一下,我并没有从jfriend00的答案中抽取这个,而是相反。

我刚才正在做,我只是想知道有没有比我更好的方法,但是没有。

你可以使用我的代码,它复制文本并显示一个工具提示。

Head

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/npm/remixicon@2.2.0/fonts/remixicon.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Body

<div class="alert alert-primary alert-dismissible mb-0 py-1" role="alert" id="liveAlert">
    <div class="container d-flex justify-content-between">
      <button type="button" class=" btn align-self-center ms-4 copytext" data-bs-toggle="tooltip" data-bs-placement="top" title=""><strong>Good news!</strong>  You just got 10% off, use your coupon <span class="fw-bold bg-secondary text-white px-2 maintext">store10off</span>. <i class="ri-file-copy-line"></i></button>
      <button type="button" class="btn align-self-center" data-bs-dismiss="alert" aria-label="Close"><strong class="fw-bold fs-4"><i class="ri-close-fill"></i></strong></button>
    </div>
    </div>

函数

<script>
    $('.copytext').click(function(){
        var thistooltip = $(this);
        var thistext = $(this).children('.maintext').text();
        navigator.clipboard.writeText(thistext);
        $(this).attr('title','copied');
        setTimeout(function(){$(thistooltip).tooltip("toggle");}, 800);
    });
</script>

换行(阿尔瓦罗·蒙托罗回答的延伸)

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

这里是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);
                    }

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