//这是代码实用位置 <!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>
示例图