如何将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 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");
}

这是这个问题最简单的解

其他回答

你可以从HTML元素的文本中复制一个单独的文本。

        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();
            }
        };
 document.getElementById('markup-copy').addEventListener('click', function() {
               var txt = "Your text Here";
                    $("<textarea/>").appendTo("body").val(txt).select().each(function () {
                    document.execCommand('copy');
                }).remove();
            });

非常简单。你必须搜索js navigator.clipboard.writeText("thistext"); 这将简单地复制文本“thistext”。现在让它工作点击,使用jquery onclick函数和存储值(你想复制的文本)在一个字符串(如果你需要,那么你可以使用DOM以及从页面获取一个值),并使用这一行复制,而不是“thistext”,传递变量!

你为什么不直接用这个代码,我不明白?

navigator.clipboard.writeText('text here...');

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