目录
document.execCommand('copy')(复制)
document.execCommand('cut')(剪切)
document.execCommand('paste')(粘贴)
应用场景:
在前端开发中经常遇到需要向系统剪切板写入内容,方便用户直接粘贴到其他应用,而不需要下载的情况,现总结如下:
Document.execCommand() 方法
传统方法,兼容性好,但已弃用。
问题是该方法只能复制选中的文本,就是说在复制前需要用到select将内容先选中。
Document.execCommand()是操作剪贴板的传统方法,
各种浏览器都支持。
它支持复制、剪切和粘贴这三个操作。
-
document.execCommand('copy')(复制)
const inputElement = document.querySelector('#input');
inputElement.select();
document.execCommand('copy');
-
document.execCommand('cut')(剪切)
const inputElement = document.querySelector('#input');
inputElement.select();
document.execCommand('cut');
-
document.execCommand('paste')(粘贴)
const pasteText = document.querySelector('#output');
pasteText.focus();
document.execCommand('paste');
如果不是复制DOM元素里的内容,而是在JS中的任意文本.
要先创建一个元素,将要复制的值放进去,再选中、复制,最后记得要移除这个元素。例
export const copyStringToClipboard = (str: string) => {
const el = document.createElement('input');
el.value = str;
el.setAttribute('readonly', '');
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
};
实际操作:
//定义函数
/**
* 复制到剪切板
* @param {String} text 文本
*/
function copyToClipboard(text) {
var textArea = document.createElement("textarea");
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
try {
var successful = document.execCommand("copy");