gpt4 book ai didi

javascript - 如何以最简单的方式使用 jQuery 将文本 (

) 复制到图像单击的剪贴板?

转载 作者:行者123 更新时间:2023-12-02 22:18:01 25 4
gpt4 key购买 nike

我正在寻找最简单的解决方案,将图像上的 html p 标记内的文本复制到剪贴板。

我尝试了此线程中的一些小型(代码明智)解决方案 Click button copy to clipboard using jQuery ,但它只是不会复制文本。就我而言,我需要它通过图像点击而不是按钮点击来工作。

$("#clipboardImage").click(function() {
$("#didText").select();
document.execCommand("copy");
alert("Text copied")
});
#didText {
color: #1816A9;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<div id="didContainer">
<p id="didText" type="text">I hopefully end up in the form field anytime soon!</p>
<img id="clipboardImage" src="" alt="Click me, to bring him down!">
</div>
<br>
<form>
Worked?
<input type="text" name="copied Text">
</form>
</html>

最佳答案

如果我理解得很清楚,您的目标是将 p 标记中的文本放入 input 字段中。

只需使用 JQuery .text() 选择文本并将其作为值放入输入字段

编辑

因此,如果主要目标是将元素中的一些文本放入剪贴板,我建议使用专用函数,有一种解决方法可以创建不可见且只读的 textarea 并将其用作“代理”将文本存储并复制到剪贴板。

注意:为了避免将文本传递到输入字段,只需删除 $("input").val(text); 行即可。

    function copyToClipboard (str) {
var el = document.createElement('textarea'); // Create a <textarea> element
el.value = str; // Set its value to the string that you want copied
el.setAttribute('readonly', ''); // Make it readonly to be tamper-proof
el.style.position = 'absolute';
el.style.left = '-9999px'; // Move outside the screen to make it invisible
document.body.appendChild(el); // Append the <textarea> element to the HTML document
var selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; // Mark as false to know no selection existed before
el.select(); // Select the <textarea> content
document.execCommand('copy'); // Copy - only works as a result of a user action (e.g. click events)
document.body.removeChild(el); // Remove the <textarea> element
if (selected) { // If a selection existed before copying
document.getSelection().removeAllRanges(); // Unselect everything on the HTML document
document.getSelection().addRange(selected); // Restore the original selection
}
};



$("#clipboardImage").click(function() {
var didText = $("#didText");
var text = didText.text();
copyToClipboard(text);
$("input").val(text);
alert("Text copied")
});
#didText {
color: #1816A9;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>

<div id="didContainer">

<p id="didText" type="text">I hopefully end up in the form field anytime soon!</p>
<img id="clipboardImage" src="" alt="Click me, to bring him down!">

</div>

<br>

<form>

Worked?
<input type="text" name="copied Text">

</form>

</html>

关于javascript - 如何以最简单的方式使用 jQuery 将文本 (<p>) 复制到图像单击的剪贴板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59321673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com