JS实现一键复制可以使用以下方法:
1、使用document.execCommand()方法实现复制:
function copyTextToClipboard(text) {
var textarea = document.createElement("textarea");
textarea.value = text;
document.body.appendChild(textarea);
textarea.select();
document.execCommand("copy");
document.body.removeChild(textarea);
}使用示例:
copyTextToClipboard("Hello World");注意:该方法在一些浏览器中可能不被支持。
2、使用Clipboard API实现复制:
function copyTextToClipboard(text) {
navigator.clipboard.writeText(text).then(function() {
console.log("Text copied to clipboard");
}, function(err) {
console.error("Failed to copy text to clipboard: ", err);
});
}使用示例:
copyTextToClipboard("Hello World");注意:该方法需要浏览器支持Clipboard API。
3、使用document.execCommand()和Range对象实现复制:
function copyTextToClipboard(text) {
var range = document.createRange();
var selection = window.getSelection();
var textarea = document.createElement("textarea");
textarea.value = text;
document.body.appendChild(textarea);
range.selectNodeContents(textarea);
selection.removeAllRanges();
selection.addRange(range);
textarea.setSelectionRange(0, textarea.value.length);
document.execCommand("copy");
document.body.removeChild(textarea);
}使用示例:
copyTextToClipboard("Hello World");



B2C电商系统商城源码支持pC+小程序+公众号+H5可打包App源...
原生开发淘宝客App,Android+ios独立开发,全开源支持二...
知识付费系统在线教育平台源码+题库系统源码,PC+公众号商业授权...
B2C单商户电商系统源码部署小程序+公众号+H5+App源码...
教育知识付费系统源码带题库功能商业授权公众号+H5源码...