700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 一键复制文本实现(navigator.clipboard 和 execCommand(废弃))

一键复制文本实现(navigator.clipboard 和 execCommand(废弃))

时间:2023-05-09 15:22:31

相关推荐

一键复制文本实现(navigator.clipboard 和 execCommand(废弃))

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('复制成功');});

码字不易,觉得有帮助的小伙伴点个赞支持下~

扫描上方二维码关注我的订阅号~

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。