如何将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,它必须被粘贴。
没有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>
我刚才正在做,我只是想知道有没有比我更好的方法,但是没有。
你可以使用我的代码,它复制文本并显示一个工具提示。
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>