一、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