<!DOCTYPE html> <html lang="en"> <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>一鍵復制demo</title> <style type="text/css"> .wrapper { position: relative; } #input { position: absolute; top: 0; left: 0; opacity: 0; z-index: -10; } .btn{ -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } #text { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } </style> </head> <body> <div class="wrapper"> <p id="text" onclick="sss()">我把你當兄弟dsadsadasdas你卻想着復制我?</p> <input type="text" id="input"> <button class="btn" onclick="copyText()">copy</button> </div> </body> <script> function copyText() { var text = document.getElementById("text").innerText; var input = document.getElementById("input"); input.value = text; // 修改文本框的內容 input.select(); // 選中文本 document.execCommand("copy"); // 執行瀏覽器復制命令 alert("復制成功"); } function sss(params) { console.log(111); } </script> </html>
ps:中間有一個不可選中文檔的css