方法一:
<span class="look-value" id="copyText">被复制的文本</span><input id="input" value="这是幕后黑手" style="opacity:0;position:absolute" /><el-button type="primary" size="small" @click="copyText">复制</el-button>
copyText() {const text = document.getElementById('copyText')!.innerText; // 复制文本const input = document.getElementById('input')! as any; // 承载复制内容input.value = text; // 修改文本框的内容input.select(); // 选中文本document.execCommand('copy'); // 执行浏览器复制命令
},
方法二:
<input ref="inputCopy" value="这是幕后黑手" style="opacity:0;position:absolute" /><el-button type="primary" size="small" @click="copyText">复制</el-button>
copyText() {const text = '被复制的文本'; // 复制文本const input = proxy.$refs.inputCopyinput.value = text; // 修改文本框的内容input.select(); // 选中文本document.execCommand('copy'); // 执行浏览器复制命令
},
注意:
input 元素,不能使用 disable 属性,也不能设置 v-if 和 hidden 隐藏。只能通过 opacity 和 position 来控制。