admin管理员组

文章数量:1394554

I'm trying to make it so that users using my script can just click on an ID from a specific website and it will copy a link to their clipboard with the text they clicked on. For example, I click on the text 1510970 on / and it copies a link .php?id= with the ID, so when I paste my copied content, it should look like .php?id=1510970.

I'm trying to make it so that users using my script can just click on an ID from a specific website and it will copy a link to their clipboard with the text they clicked on. For example, I click on the text 1510970 on http://www.myurl./ and it copies a link http://www.myurl./viewReport.php?id= with the ID, so when I paste my copied content, it should look like http://www.myurl./viewReport.php?id=1510970.

Share Improve this question asked Aug 1, 2018 at 4:01 Lord NazoLord Nazo 371 gold badge1 silver badge6 bronze badges 1
  • w3schools./howto/tryit.asp?filename=tryhow_js_copy_clipboard – Sakkeer A Commented Aug 1, 2018 at 4:05
Add a ment  | 

2 Answers 2

Reset to default 4

If you want to ensure patibility with all major browsers, you can use the following workaround:

  • Create a <textarea> element to be appended to the document.
  • Set its value to the string that we want to copy to the clipboard.
  • Append the <textarea> element to the HTML document.
  • Use HTMLInputElement.select() to select the contents of the <textarea> element.
  • Use Document.execCommand('copy') to copy the contents of the <textarea> to the clipboard.
  • Remove the <textarea> element from the document.

const copyToClipboard = str => {
  const el = document.createElement('textarea');
  el.value = str;
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
};

const url ='http://www.myurl./viewReport.php?id=';

document.getElementById('myItem').addEventListener('click', function(e){ 
  let myUrl =  url + e.target.dataset.page_id;
  copyToClipboard( myUrl );
  alert(myUrl + ' copied to clipboard!')
});
<div id="myItem" data-page_id="1510970">1510970</div>

STYLE : Injecting a textarea in your HTML can cause some rendering issues. To avoid them, use CSS to hide the element, give it an absolute position, and negative y-coordinates. (These are just examples.)

You can do it

function copyText(){
    var url = "http://www.myurl./viewReport.php?id=";
    var text = document.getElementById("myText").innerHTML;
    var textCopy = document.getElementById("myText");
    textCopy.value = url + text;    
    document.execCommand("copy");
    }
<div id="myText" onclick="copyText()">Text you want to copy</div>

本文标签: javascriptClick on text to copy a link to the clipboardStack Overflow