Javascript - 单击时复制文本字符串

Mat*_*hew 26 javascript clipboard copy-paste

我花了20分钟在网上搜索这个,但找不到它.我想要的是能够在没有按钮的情况下复制文本字符串.文本字符串将位于"span"类中.

  1. 用户将鼠标悬停在文本字符串上
  2. 用户单击文本字符串
  3. 文本字符串被复制到剪贴板

任何帮助将不胜感激.谢谢!

gue*_*314 33

您可以将copy事件附加到<span>元素,document.execCommand("copy")在事件处理程序中使用,设置event.clipboardDataspan .textContentwith .setData()方法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"))
  }
});
Run Code Online (Sandbox Code Playgroud)
<span>text</span>
Run Code Online (Sandbox Code Playgroud)

  • 如果用户已经选择了一些文本,则此代码很容易出现问题。有关完整解决方案,请参阅 /sf/answers/3778445751/。 (2认同)

Gib*_*olt 26

使用剪贴板 API!

最简单的现代解决方案是:

navigator.clipboard.writeText(value)
Run Code Online (Sandbox Code Playgroud)

稍后可以通过以下方式访问该值:

navigator.clipboard.readText()
Run Code Online (Sandbox Code Playgroud)

注意:这需要,这意味着默认情况下https它不会工作localhost

注意:要在 an 中使用iframe,您需要添加写入(可能还有读取)权限

<iframe src='' allow='clipboard-read; clipboard-write'/>
Run Code Online (Sandbox Code Playgroud)

注意:要在浏览器扩展程序中使用(在网页上),您需要:

  • 来自用户触发事件的调用 ( click...)
  • 将 ' clipboardWrite' 权限添加到清单中

注意:要在开发控制台中使用,请copy()改用

copy('string')
Run Code Online (Sandbox Code Playgroud)

W3Schools 教程

我可以用吗

  • 最后!我正想说“没有人考虑过使用‘navigator.clipboard’吗???” (2认同)
  • 我实际上很惊讶这不是最佳答案。剪贴板 API 是 OP (2认同)

pra*_*nth 22

试试这个 .document.execCommand('copy')

  1. 单击元素并复制文本并使用tmp input元素发布
  2. 然后从此输入中复制文本

function copy(that){
var inp =document.createElement('input');
document.body.appendChild(inp)
inp.value =that.textContent
inp.select();
document.execCommand('copy',false);
inp.remove();
}
Run Code Online (Sandbox Code Playgroud)
<p onclick="copy(this)">hello man</p>
Run Code Online (Sandbox Code Playgroud)


Bla*_*mba 17

这是Code笔.

<link href='https://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'> 
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Jquery代码在这里

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}
Run Code Online (Sandbox Code Playgroud)

  • 人们将会遇到关于搜索如何复制文本的问题,而jQuery可能是他们的选择,即使op可能不会直接从我的答案中受益,但很多社区成员将会 (7认同)

Nat*_*hat 8

除了复制文本之外,您还必须确保在复制到剪贴板后任何先前选择的组件仍保持选中状态。

这是完整的代码:

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
  }
};
Run Code Online (Sandbox Code Playgroud)

ps 添加

  • 这应该是正确答案。接受的答案是错误的。 (2认同)

小智 5

execCommand ()方法以前用于将文本复制到剪贴板,现已弃用,不应在现代 Web 开发中使用。相反,navigator.clipboard API 现在是在浏览器中执行剪贴板操作的推荐方法。该 API 是内置浏览器 Web API,这意味着它既安全又易于集成到您的 Web 应用程序中,而无需任何外部依赖项。

Clipboard API 可用于在 Web 应用程序中实现剪切、复制和粘贴功能。

以下代码片段将仅复制单击的 span 元素的内容。

jQuery

$(document).on('click', 'span', function() {
      let copyText = $(this)[0].textContent
      navigator.clipboard.writeText(copyText)
})
Run Code Online (Sandbox Code Playgroud)

JavaScript

document.addEventListener('click', function(event) {
  if (event.target.tagName === 'SPAN') {
    let copyText = event.target.textContent;
    navigator.clipboard.writeText(copyText);
  }
});
Run Code Online (Sandbox Code Playgroud)

请随意相应地定制。