📅  最后修改于: 2023-12-03 15:08:10.002000             🧑  作者: Mango
在开发web应用程序时,经常需要将用户输入、网页内容、或者其他数据复制到剪贴板中。Javascript DOM提供了一种简单的方法来实现这个过程,无需使用Flash或者其他插件。
以下是使用Javascript DOM实现复制到剪贴板的代码片段:
function copyToClipboard(text) {
var dummy = document.createElement("textarea");
// Add the text to the dummy textarea
dummy.value = text;
// Hide the textarea from the user
dummy.style.opacity = "0";
dummy.style.position = "absolute";
dummy.style.left = "-9999px";
// Add the dummy textarea to the page
document.body.appendChild(dummy);
// Select the text in the dummy textarea
dummy.select();
dummy.setSelectionRange(0, 99999); // For mobile devices
// Copy the selected text to the clipboard
document.execCommand("copy");
// Remove the dummy textarea from the page
document.body.removeChild(dummy);
}
以上代码的功能是:将给定的文本内容复制到剪贴板。
var dummy = document.createElement("textarea");
dummy.value = text;
dummy.style.opacity = "0";
dummy.style.position = "absolute";
dummy.style.left = "-9999px";
document.body.appendChild(dummy);
dummy.select();
dummy.setSelectionRange(0, 99999); // For mobile devices
document.execCommand("copy");
document.body.removeChild(dummy);
你可以在自己的网站中,添加一个按钮或者链接,然后在点击后使用以上的代码来复制文本到剪贴板中。
例如,下面的代码创建了一个按钮,它的点击事件会将文本“Hello World”复制到剪贴板中:
<button onclick="copyToClipboard('Hello World')">复制到剪贴板</button>
使用Javascript DOM很容易地将文本复制到剪贴板中,这样可以方便用户在接下来的操作中直接使用这些文本。尽管不是所有的浏览器都支持该方法,但是在大多数常用浏览器中是可以正常使用的。