js 如何实现 copy 一段文本内容用纯js实现
可以使用以下方法来实现复制一段文本内容:
- 创建一个文本框元素并将其隐藏
var text = "hello world";
var input = document.createElement("textarea");
input.value = text;
input.style.opacity = "0";
document.body.appendChild(input);
- 选中文本框中的内容
input.select();
- 复制选中的内容
document.execCommand("copy");
- 移除文本框元素
document.body.removeChild(input);
完整代码如下:
function copyText(text) {
var input = document.createElement("textarea");
input.value = text;
input.style.opacity = "0";
document.body.appendChild(input);
input.select();
document.execCommand("copy");
document.body.removeChild(input);
}
可以直接调用该函数来复制一段文本内容:
copyText("hello world");
原文地址: https://www.cveoy.top/t/topic/bgcI 著作权归作者所有。请勿转载和采集!