单击复制文本字符串 [英] Copy text string on click

查看:82
本文介绍了单击复制文本字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了20分钟在网上进行搜索,但找不到。我想要的是能够在没有按钮的情况下单击复制文本字符串。文本字符串将在 span类中。

I spent a good 20 min searching online for this, but couldn't find it. What I want is to to be able to copy a text string on click without a button. The text string will be inside a "span" class.


  1. 用户将鼠标悬停在文本字符串上

  2. 用户单击文本字符串

  3. 文本字符串已复制到剪贴板

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

Any help would be greatly appreciated. Thanks!

推荐答案

您可以将 copy 事件附加到< span> 元素,在事件处理程序中使用 document.execCommand( copy),设置 event。剪贴板数据 span .textContent .setData() event.clipboardData

You can attach copy event to <span> element, use document.execCommand("copy") within event handler, set event.clipboardData to span .textContent with .setData() method of 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>

这篇关于单击复制文本字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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