单击时复制文本字符串

时间:2017-07-13 04:22:50

标签: javascript clipboard copy-paste

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

  1. 用户将鼠标悬停在文字字符串
  2. 用户点击文字字符串
  3. 文本字符串被复制到剪贴板
  4. 非常感谢任何帮助。谢谢!

8 个答案:

答案 0 :(得分:30)

您可以将copy事件附加到<span>元素,在事件处理程序中使用document.execCommand("copy"),将event.clipboardData设置为span .textContent {{ 1}} .setData()

的方法

&#13;
&#13;
event.clipboardData
&#13;
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"))
  }
});
&#13;
&#13;
&#13;

答案 1 :(得分:18)

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

  1. 单击元素并复制文本并使用tmp input element
  2. 发布
  3. 然后从此输入中复制文本
  4. 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>

答案 2 :(得分:16)

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 Code

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

答案 3 :(得分:3)

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

这是完整的代码:

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

答案 4 :(得分:2)

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

答案 5 :(得分:0)

guest271314's answer应用于多个元素:

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>

答案 6 :(得分:0)

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

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

答案 7 :(得分:-5)

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>