//這是代碼實用位置 <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <button id="a-1-1-A" onclick="copyText1(this.id)">點擊復制id,兼容寫法</button> <script> function handleCopyValue(text) { //瀏覽器禁用了非安全域的 navigator.clipboard 對象 //在線上環境會報錯 TypeError: Cannot read properties of undefined (reading 'writeText') if (!navigator.clipboard && window.isSecureContext) { return navigator.clipboard.writeText(text); }else { // 判斷是否支持拷貝 if (!document.execCommand('copy')) return Promise.reject() // 創建標簽,并隱藏 const textArea = document.createElement('textarea') textArea.style.position = 'fixed' textArea.style.top = textArea.style.left = '-100vh' textArea.style.opacity = '0' textArea.value = text document.body.appendChild(textArea) // 聚焦、復制 textArea.focus() textArea.select() return new Promise((resolve, reject) => { // 不知為何,必須寫這個三目,不然copy不上 document.execCommand('copy') ? resolve() : reject() textArea.remove() }) }}/*點擊復制 ,val是需要復制的值 */ function copyText1(val){ handleCopyValue(val) .then(() => { alert('復制成功') }) .catch(() => { alert('自動復制失敗,請手動復制') }) }</script> </body> </html>
示例圖