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
2 Answers
Reset to default 4If 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
版权声明:本文标题:javascript - Click on text to copy a link to the clipboard - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744100445a2590847.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论