execCommand
已经被废弃了,所以尽量不要再使用了!
当然如果遇到execCommand
失效(http情况下),暂时可以继续使用execCommand
推荐写法:
// navigator clipboard 需要https等安全上下文if (navigator.clipboard && window.isSecureContext) {// navigator clipboard 向剪贴板写文本navigator.clipboard.writeText(this.content).then(() => {this.$message.success('复制成功');});} else {// 创建text arealet textArea = document.createElement('textarea');textArea.value = this.content;// 使text area不在viewport,同时设置不可见textArea.style.position = 'absolute';textArea.style.opacity = '0';textArea.style.left = '-999999px';textArea.style.top = '-999999px';document.body.appendChild(textArea);textArea.focus();textArea.select();// 执行复制命令并移除文本框document.execCommand('copy');this.$message.success(`复制成功: ${this.content}`);textArea.remove();}
使用navigator.clipboard.writeText(value);
相比以前更加简洁。
//旧:let oInput = document.createElement('input');oInput.value = value;document.body.appendChild(oInput);oInput.select(); // 选择对象;document.execCommand("Copy"); // 执行浏览器复制命令this.$Message.success('复制成功');oInput.remove()//新:navigator.clipboard.writeText(value).then(() => {this.$Message.success('复制成功');});