JavaScript 复制到剪贴板不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47931843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript copy to clipboard not working
提问by Intervalia
I have a function in my script that gives me an error. The function purpose is to copy text from static panel(not textbox or input) with onClick event.
我的脚本中有一个函数给我一个错误。功能目的是使用 onClick 事件从静态面板(不是文本框或输入)复制文本。
Uncaught TypeError: copyText.select is not a function
未捕获的类型错误:copyText.select 不是函数
The thing i want is to make the user able to click the text and it's get copied to his clipboard.
我想要的是让用户能够单击文本并将其复制到他的剪贴板。
Maybe you can offer better function that works?
也许您可以提供更好的功能?
https://codepen.io/abooo/pen/jYMMMN?editors=1010
https://codepen.io/abooo/pen/jYMMMN?editors=1010
function myFunction() {
var copyText = document.getElementById("display");
copyText.select();
document.execCommand("Copy");
alert("Copied the text: " + copyText.value);
}
From w3schools
来自 w3schools
回答by Intervalia
This will allow you to copy the text of an element. Though I have not tested it with complicated layout.
这将允许您复制元素的文本。虽然我没有用复杂的布局测试过它。
If you want to use this then remove the alerts and provide a better way to let the user know the content was copied.
如果您想使用它,请删除警报并提供一种更好的方式让用户知道内容已被复制。
SAFARI: This does not work on Safari before version 10.0. But as of Safari 10.0this now works.
SAFARI:这在 10.0 版之前的 Safari 上不起作用。但是从Safari 10.0 开始,这现在可以工作了。
function copyText(element) {
var range, selection, worked;
if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
try {
document.execCommand('copy');
alert('text copied');
}
catch (err) {
alert('unable to copy text');
}
}
<h1 id='display' onClick='copyText(this)'>Text Sample</h1>
If you want to use this on an <input>or <textarea>element then let me know the code is different.
如果你想在一个<input>或<textarea>元素上使用它,那么让我知道代码是不同的。
The try/catch is for older versions of Safari that would throw an exception. So if you don't plan to support Safari before version 10.0 then you can remove it.
try/catch 适用于会引发异常的旧版 Safari。因此,如果您不打算在 10.0 版之前支持 Safari,那么您可以将其删除。
回答by Hike Nalbandyan
Great answer by Intervalia.
Intervalia 的出色回答。
Small improvement to it, sometimes the clicked element is not the one you want to copy.
So I suggest you pass the id of the element you want to copy.
对它的小改进,有时单击的元素不是您想要复制的元素。
所以我建议你传递你想要复制的元素的id。
<button onClick='copyText("display")'> Copy </button>
<h1 id='display'> Text Sample </h1>
And then, in the first line of your function do
然后,在你的函数的第一行做
element = document.getElementById(element);
Not much of a difference but I think it's more useful this way.
没有太大区别,但我认为这种方式更有用。
回答by mac
select()method is used to select the contents of text fields. it won't work on h1element.
select()方法用于选择文本字段的内容。它不适用于h1元素。
回答by Coola
A more recent solution (year 2020) uses the new Clipboard API writeText methodwhich is supported by most modern browsers (see Can I usefor more details).
最近的解决方案(2020 年)使用了大多数现代浏览器都支持的新剪贴板 API writeText 方法(有关更多详细信息,请参阅Can I use)。
//If you want to copyText from Element
function copyTextFromElement(elementID) {
let element = document.getElementById(elementID); //select the element
let elementText = element.textContent; //get the text content from the element
copyText(elementText); //use the copyText function below
}
//If you only want to put some Text in the Clipboard just use this function
// and pass the string to copied as the argument.
function copyText(text) {
navigator.clipboard.writeText(text);
}
<div id="mytext">This is some text that needs to be copied</div>
<button onclick="copyTextFromElement('mytext')">Copy</button>
回答by Andres C.
hi so I looked into it and since you are not using a textInput you cannot just use the .select()function. I borrowed some code from a fellow stack overflow developer Jason on how to highlight an item in javaScript
嗨,所以我调查了它,因为您没有使用 textInput,所以您不能只使用该.select()功能。我从堆栈溢出开发人员 Jason 那里借用了一些关于如何在 javaScript 中突出显示项目的代码
selecting text in an element akin to highlighting with your mouse.
function selectedText(element)(){
function selectedText(element)(){
var doc = document,
text = doc.getElementById(element)
range, selection;
if(doc.body.createTextRange){
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
}
else if(window.getSelection){
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
return range;
I then modified it to return the range. and with that all you would have to do is
然后我修改它以返回范围。有了这个,你所要做的就是
document.onclick = function(e){
if(e.target.className === 'click'){
var copytext = SelectText('display');
document.execCommand("copy");
alert("Copied the text: " + copytext);
}
}
the key part here is that the string passed in to .execCommand() is lower case 'copy'
这里的关键部分是传入的字符串 .execCommand() is lower case 'copy'

