- 用户将鼠标悬停在文本字符串上
- 用户点击文本字符串
- 文本字符串被复制到剪贴板
您可以将copy
事件附加到<span>
元素上,在事件处理程序中使用document.execCommand("copy")
,使用event.clipboardData
和.setData()
方法将span
.textContent
设置为event.clipboardData
const span = document.querySelector("span");
span.onclick = function() {
document.execCommand("copy");
}
span.addEventListener("copy", function(event) {
event.preventDefault();
if (event.clipboardData) {
event.clipboardData.setData("text/plain", span.textContent);
console.log(event.clipboardData.getData("text"))
}
});
<span>text</span>
copy
事件附加到一个元素上,在事件处理程序中设置剪贴板数据。 - guest271314clipboardData
?例如从另一个事件处理程序,比如单击另一个元素的事件处理程序中获取。但是“复制”事件没有触发。 - Chloe试试这个。document.execCommand('copy')
function copy(that){
var inp =document.createElement('input');
document.body.appendChild(inp)
inp.value =that.textContent
inp.select();
document.execCommand('copy',false);
inp.remove();
}
<p onclick="copy(this)">hello man</p>
最简单的现代解决方案是:
navigator.clipboard.writeText(value)
该值以后可以通过以下方式访问:
navigator.clipboard.readText()
https
,因此默认情况下无法在 localhost
上运行。
注意:要在浏览器扩展程序(网页)中使用,您需要执行以下操作之一:NOTE: To use in an
iframe
, you'll need to add write (and maybe read) permissions
<iframe src='' allow='clipboard-read; clipboard-write'/>
NOTE: To use in the dev console, use
copy()
instead
copy('string')
navigator.clipboard
吗?” - user14018874未捕获的类型错误:navigator.clipboard 未定义
- mtoloo<link href='https://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
<p style="color:wheat;font-size:55px;text-align:center;">How to copy a TEXT to Clipboard on a Button-Click</p>
<center>
<p id="p1">This is TEXT 1</p>
<p id="p2">This is TEXT 2</p><br/>
<button onclick="copyToClipboard('#p1')">Copy TEXT 1</button>
<button onclick="copyToClipboard('#p2')">Copy TEXT 2</button>
<br/><br/><input class="textBox" type="text" id="" placeholder="Dont belive me?..TEST it here..;)" />
</center>
Jquery的代码在这里
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
在复制文本的同时,您还需要确保在将其复制到剪贴板后,任何先前选择的组件仍然保持选中状态。
const copyToClipboard = str => {
const 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
const selected =
document.getSelection().rangeCount > 0 // Check if there is any content selected previously
? document.getSelection().getRangeAt(0) // Store selection if found
: 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
}
};
添加来源请参考此链接
。guest271314的回答应用于多个元素:
spans = document.querySelectorAll(".class");
for (const span of spans) {
span.onclick = function() {
document.execCommand("copy");
}
span.addEventListener("copy", function(event) {
event.preventDefault();
if (event.clipboardData) {
event.clipboardData.setData("text/plain", span.textContent);
console.log(event.clipboardData.getData("text"))
}
});
}
<span class="class">text</span>
<br>
<span class="class">text2</span>
execCommand() 方法曾经用于将文本复制到剪贴板,但已被弃用,在现代 Web 开发中不应再使用。相反,navigator.clipboard API 现在是浏览器中执行剪贴板操作的推荐方式。该 API 是内置的浏览器 Web API,这意味着它既安全又易于集成到您的 Web 应用程序中,无需任何外部依赖。
剪贴板 API 可用于在 Web 应用程序中实现剪切、复制和粘贴功能。
以下代码片段仅会复制所点击的 span 元素的内容。
jQuery:
$(document).on('click', 'span', function() {
let copyText = $(this)[0].textContent
navigator.clipboard.writeText(copyText)
})
Javascript
document.addEventListener('click', function(event) {
if (event.target.tagName === 'SPAN') {
let copyText = event.target.textContent;
navigator.clipboard.writeText(copyText);
}
});
可以根据需要进行自定义。
这是最合适的方法。它将复制所有带有“copy”类的元素中的文本。
var copy = document.querySelectorAll(".copy");
for (const copied of copy) {
copied.onclick = function() {
document.execCommand("copy");
};
copied.addEventListener("copy", function(event) {
event.preventDefault();
if (event.clipboardData) {
event.clipboardData.setData("text/plain", copied.textContent);
console.log(event.clipboardData.getData("text"))
};
});
};
.copy {
cursor: copy;
}
<p><span class="copy">Text</span></p>
<p><span class="copy">More Text</span></p>
<p><span class="copy">Even More Text</span></p>
HTML:
<button type='button' id='btn'>Copy</button>
JS
document.querySelect('#btn').addEventListener('click', function() {
copyToClipboard('copy this text');
});
JS / 函数:
function copyToClipboard(text) {
var selected = false;
var el = document.createElement('textarea');
el.value = text;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
if (document.getSelection().rangeCount > 0) {
selected = document.getSelection().getRangeAt(0)
}
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
};
你也可以使用 onclick,像这样:
function copyCode() {
const Code = document.querySelector("input");
Code.select();
document.execCommand("copy", false);
}
<input type="input" />
<button onclick={copyCode()}>Copy</button>