单击复制文本字符串

Copy text string on click

我花了 20 分钟在线搜索此内容,但找不到。我想要的是能够在单击 而无需按钮 时复制文本字符串。文本字符串将在 "span" class.

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

如有任何帮助,我们将不胜感激。谢谢!

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

  1. 单击该元素并复制文本,然后 post 使用 tmp 输入元素
  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();
}
<p onclick="copy(this)">hello man</p>

This is the Code pen.

<link href='https://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'> 
<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>

Jquery 代码在这里

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

您可以将 copy 事件附加到 <span> 元素,在事件处理程序中使用 document.execCommand("copy"),将 event.clipboardData 设置为 span .textContent .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"))
  }
});
<span>text</span>

HTML:

<button type='button' id='btn'>Copy</button>

JS

document.querySelect('#btn').addEventListener('click', function() {
   copyToClipboard('copy this text');
});

JS/函数:

function copyToClipboard(text) {
    var selected = false;
    var el = document.createElement('textarea');
    el.value = text;
    el.setAttribute('readonly', '');
    el.style.position = 'absolute';
    el.style.left = '-9999px';
    document.body.appendChild(el);
    if (document.getSelection().rangeCount > 0) {
        selected = document.getSelection().getRangeAt(0)
    }
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);
    if (selected) {
        document.getSelection().removeAllRanges();
        document.getSelection().addRange(selected);
    }
};

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

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

完整代码如下:

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
  }
};

ps 添加 source

应用于多个元素:

spans = document.querySelectorAll(".class");
for (const span of spans) {
  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 class="class">text</span>
<br>
<span class="class">text2</span>

这是最合适的方法。它将复制元素中带有 class“复制”的所有文本。

var copy = document.querySelectorAll(".copy"); 

for (const copied of copy) { 
  copied.onclick = function() { 
    document.execCommand("copy"); 
  };  
  copied.addEventListener("copy", function(event) { 
    event.preventDefault(); 
    if (event.clipboardData) { 
      event.clipboardData.setData("text/plain", copied.textContent);
      console.log(event.clipboardData.getData("text"))
    };
  });
};
.copy {
            
  cursor: copy;
            
}
<p><span class="copy">Text</span></p>
<p><span class="copy">More Text</span></p>
<p><span class="copy">Even More Text</span></p>

使用剪贴板API!

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

navigator.clipboard.writeText(value)

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

navigator.clipboard.readText()

NOTE: To use in an iframe, you'll need to add write (and maybe read) permissions

<iframe src='' allow='clipboard-read; clipboard-write'/>

NOTE: To use in an browser extension (on a webpage), you'll need either to:

  • call from a user triggered event (click...)
  • add the 'clipboardWrite' permission to the manifest

NOTE: To use in the dev console, use copy() instead

copy('string')

W3Schools Tutorial

CanIUse