创建没有输入文本框的复制按钮 [英] Create a Copy Button Without an Input Text Box

查看:37
本文介绍了创建没有输入文本框的复制按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些 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>

这篇关于创建没有输入文本框的复制按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆