从标签单击时复制文本<p>


<div class="d-flex flex-row justify-content-between">
<p class="mb-0 me-1 py-2 ps-4 add-text" id="p1">ygwbfewilskfhnewisfklnewiofjfhjky</p>
<button class="btn-primary w-20 px-3 copy-btn" onclick="copyToClipboard('#p1')">Copy<i class="fa-regular fa-copy ps-2"></i></button>
</div>

JS:

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

我想复制p中的文本id="p1"

我尝试过这个方法,因为我看到它对别人有效,但对我不起作用

你的代码很好,没有任何问题。我认为您可能忘记向它添加jQuery了。您可以通过在HTML代码的<head>标记中添加以下代码来做到这一点:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

您的代码运行完全正常,您可以在这里查看它如果它仍然不起作用,您可能已经阻止了JavaScript。检查确保你没有一个扩展阻止JS,检查你的浏览器设置,以及确保JS是允许的。

(我需要有代码,因为它是一个相互依存的链接)

<div class="d-flex flex-row justify-content-between">
<p class="mb-0 me-1 py-2 ps-4 add-text" id="p1">ygwbfewilskfhnewisfklnewiofjfhjky</p>
<button class="btn-primary w-20 px-3 copy-btn" onclick="copyToClipboard('#p1')">Copy<i class="fa-regular fa-copy ps-2"></i></button>
</div>
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}

下面是这样做的一个普通版本。如果你读了我对OP问题的评论,你会发现jQuery方法依赖于Adobe Flash,并不是所有浏览器都完全支持。

function copyToClipboard() {
var range = document.createRange();
range.selectNode(document.getElementById("p1"));
window.getSelection().removeAllRanges(); // clear current selection
window.getSelection().addRange(range); // to select text
document.execCommand("copy");
window.getSelection().removeAllRanges();// to deselect
}
<div class="d-flex flex-row justify-content-between">
<p class="mb-0 me-1 py-2 ps-4 add-text" id="p1">ygwbfewilskfhnewisfklnewiofjfhjky</p>
<button class="btn-primary w-20 px-3 copy-btn" onclick="copyToClipboard('#p1')">Copy<i class="fa-regular fa-copy ps-2"></i></button>
</div>

最新更新