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


当前回答

<div class="form-group">
    <label class="font-normal MyText">MyText to copy</label>&nbsp;
    <button type="button" class="btn btn-default btn-xs btnCopy" data="MyText">Copy</button>
</div>


$(".btnCopy").click(function () {
        var element = $(this).attr("data");
        copyToClipboard($('.' + element));
  });

function copyToClipboard(element) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($(element).text()).select();
    document.execCommand("copy");
    $temp.remove();
}

其他回答

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

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;" />
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link href="css/index.css" rel="stylesheet" />
    <script src="js/jquery-2.1.4.min.js"></script>
    <script>
        function copy()
        {
            try
            {
                $('#txt').select();
                document.execCommand('copy');
            }
            catch(e)
            {
                alert(e);
            }
        }
    </script>
</head>
<body>
    <h4 align="center">Copy your code</h4>
    <textarea id="txt" style="width:100%;height:300px;"></textarea>
    <br /><br /><br />
    <div align="center"><span class="btn-md" onclick="copy();">copy</span></div>
</body>
</html>

文本复制是在文本输入,如:< input type="text" id="copyText" name="copyText">和,在按钮点击上面的文本应该被复制到剪贴板,所以按钮是像:<button type="submit" id="copy_button" data-clipboard-target='copyText'>复制</button>你的脚本应该像:

<script language="JavaScript">
$(document).ready(function() {
var clip = new ZeroClipboard($("#copy_button"), {
  moviePath: "ZeroClipboard.swf"
}); 
});

</script>

CDN文件

(zeroclipboard.swf): (zeroclipboard.js):

注意:ZeroClipboard.swf和ZeroClipboard.js”文件应该和你使用这个功能的文件在同一个文件夹中,或者你必须包括像我们包括<script src=""></script>在我们的页面上。

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

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

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>