点击链接或按钮时复制文本

11

我是新手网站开发者,想知道如何使用HTML、PHP或JavaScript让用户在点击链接时自动复制代码到剪贴板。例如,我正在尝试创建个人网站,当用户在我的网站上单击链接或按钮时,应自动将文本代码复制到剪贴板。我见过像retailmenot.com这样的网站做到了这一点:

enter image description here

如果您能给出一个示例就更好了。


更新:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>


$("#link").click(function(){
  var holdtext = $("#clipboard").innerText;
  Copied = holdtext.createTextRange();
  Copied.execCommand("Copy");
});


</script>
</head>
<body>

<hr>
<a href="http://www.w3schools.com" style="font-family:arial;color:black;font-size:25px;">Click here to copy the Code</a> <button onclick="copyToClipboard()">Copy Text</button>
<hr>

</body>
</html>

我认为Javascript没有内置的复制/粘贴剪贴板的方法。有一些基于Flash的解决方案。 - Barmar
1
一篇长篇讨论:https://dev59.com/fHRC5IYBdhLWcg3wJNcN - Peter van der Wal
2个回答

3

以下是可以帮助您或日后参考的函数。

    function copyToClipboard(id) {
    var text = $("#td_id_" + id).text(); //getting the text from that particular Row
    //window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
    if (window.clipboardData && window.clipboardData.setData) {
        // IE specific code path to prevent textarea being shown while dialog is visible.
        return clipboardData.setData("Text", text); 

    } else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in MS Edge.
        document.body.appendChild(textarea);
        textarea.select();
        try {
            return document.execCommand("copy");  // Security exception may be thrown by some browsers.
        } catch (ex) {
            console.warn("Copy to clipboard failed.", ex);
            return false;
        } finally {
            document.body.removeChild(textarea);
        }
    }
  }

各浏览器中的单元测试尚未完成。


1
尝试这个。
$("#link").click(function(){
  var holdtext = $("#clipboard").innerText;
  Copied = holdtext.createTextRange();
  Copied.execCommand("Copy");
});

这只在IE中有效(https://dev59.com/32Ei5IYBdhLWcg3wJpcl) - Lego

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接