创建没有输入文本框的复制按钮
我需要一些 JavaScript 来制作一些文本,以便在您单击按钮时复制剪贴板.我附上了下面的按钮 HTML.注意:我有不止一个按钮.
I need some JavaScript to make some text to copy your clipboard when you click a button. I have attached the button HTML below. Note: I have more than one button.
<button id="TextToCopy"><img src="button_image.png" onclick="ClipBoard(this)"></button>
我想为每个按钮做一个这样的 if 语句,但不知道如何复制文本.
I was thinking about doing an if statement like this for each button but don't know what to do to copy the text.
function ClipBoard(x) {
if (x.id == "TextToCopy")
var copyText = "TextToCopy";
你可以用这种函数来做:
You can use this kind of function to do it:
(请注意,由于您不应该使用内联 JavaScript,因此我在 HTML 中删除了您的 onclick
.)
(Note that as you shouldn't use inline JavaScript, I removed your onclick
in the HTML.)
function Clipboard_CopyTo(value) {
var tempInput = document.createElement("input");
tempInput.value = value;
document.body.appendChild(tempInput);
tempInput.select();
document.execCommand("copy");
document.body.removeChild(tempInput);
}
document.querySelector('#Copy').onclick = function() {
Clipboard_CopyTo('Text to copy!');
}
<button id="Copy">Copy "Text to copy!" to clipboard</button>
<br><br>
<input placeholder="Paste here, to try!">
此函数创建一个临时输入,在复制文本后删除该输入.
This function creates a temporary input that is removed after the text has been copied.
希望有帮助.
⋅ ⋅ ⋅
对于多行文本,可以使用 textarea
.
And for multiline texts, textarea
can be used.
function Clipboard_CopyTo(value) {
var tempInput = document.createElement("textarea");
tempInput.value = value;
document.body.appendChild(tempInput);
tempInput.select();
document.execCommand("copy");
document.body.removeChild(tempInput);
}
document.querySelector('#Copy').onclick = function() {
Clipboard_CopyTo('Text to copy\non multiple lines.');
}
<button id="Copy">Copy to clipboard</button>
<br><br>
<textarea placeholder="Paste here, to try!"></textarea>