使用JS實現復制粘貼功能
如果嵌套太多使用這個:
// 複製單號1
// 第一步把這個放到頁面
// <div style="position:absolute; opacity: 0;" id="copy1"></div>
// 第二步增加按鈕設置點擊事件
// 第三如下:
copyNo() {
const a = document.createElement('textarea')
let b;
if (this.myshow) {
a.innerText = this.aaa[this.aaa.ccc] || '';
} else {
a.innerText = this.bb|| '';
}
b = document.getElementById('copy1')
a.setAttribute('id', 'copy');
b.innerHTML = "";
b.appendChild(a)
let e: any = document.getElementById("copy");
e.select(); // 選擇對象
document.execCommand("Copy"); // 執行瀏覽器復制命令
if (a.value) {
alert('Copy Success!');
} else {
alert('The copied content is empty!');
}
}
// 複製單號2
如果是簡單地輸入框沒有太多嵌套,使用這個:
<!DOCTYPE html> <html> <head> <script type="text/javascript"> function copyLink(){ var e = document.getElementById("copy"); e.select(); // 選擇對象 document.execCommand("Copy"); // 執行瀏覽器復制命令 alert("內容復制成功!"); } </script> </head> <body> <!-- <textarea id="copy">待復制的內容</textarea> --> <input type="text" id="copy"> <input type="button" onclick="copyLink()" value="點擊復制"></input> </body> </html>