写我的项目的时候须要用到剪切板的性能, 参考我的项目里的写法,用到了document.execCommand()办法。

1 const text = "这是待复制待内容"  2 const input = document.createElement('input'); // 间接构建input3 document.body.appendChild(input);  // 增加长期元素4 input.value =  text;  // 设置内容5 input.select();  // 抉择元素6 const result = document.execCommand('copy'); // 执行复制7 document.body.removeChild(input);  // 删除长期元素

看webstrom提醒发现,这个办法是弃用的符号。

之后就想着看看当初用什么来代替。

查看官网文档

MD5官网文档: https://developer.mozilla.org...

同样能够看到,说该办法曾经弃用了。

剪贴板 Clipboard API 为 Navigator 接口增加了只读属性 clipboard,该属性返回一个能够读写剪切板内容的 Clipboard 对象。

示例中举荐写法:

复制到剪切板:

const text = "这是待复制待内容";navigator.clipboard.writeText(text).then(        () => {          console.log("胜利");        },        () => {          console.log("失败");        }

从剪切板中读取:

 navigator.clipboard.readText().then(    text => console.log('剪切板信息为', text));

在剪切板为空或者不蕴含文本时,readText() 会返回一个空字符串。

运行后果:

不过依据兼容性表看, 有一些浏览器并不兼容这个api, 比方火狐。

尽管document.execCommand曾经过期, 但显著有更大的兼容性。

如同 Clipboard API 文档中所写:

The navigator.clipboard API is a recent addition to the specification and may not be fully implemented in all browsers.

对该 API 的反对还不宽泛。

所以最初还是用了document.execCommand("copy");

使其有更宽泛的浏览器覆盖范围。