一、HTML 代码 注:只能使用input或者textarea等
<div>
<input type="text" id='codeInput' readonly>
<a οnclick='copyClick()'>复制</a>
</div>
二、JavaScript
function copyClick () {
let inputText = document.getElementById('codeInput'); //获取input
inputText.focus(); // 获取焦点到input
inputText.setSelectionRange(0, inputText.value.length); //选择复制的内容
let isSuccess = document.execCommand('copy', true); //执行复制操作
inputText.setSelectionRange(0, 0); //取消选择
if (isSuccess) {
this.showAlert('复制成功');
} else {
this.showAlert('请手动复制');
}
}
三、浏览器兼容性参考如下
https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLInputElement/setSelectionRange