如何使用 JavaScript 将文本复制到剪贴板?
cssjavascriptweb developmentfront end technology
以下是使用 JavaScript 将文本复制到剪贴板的代码 −
示例
<!DOCTYPE html> <html> <head> <style> button { border: none; outline: none; background-color: rgb(191, 187, 255); color: black; font-weight: bold; padding: 10px; } input { padding: 10px; } </style> </head> <body> <h1>Clipboard example</h1> <h2>Click the button below to copy text and paste it somewhere</h2> <input type="text" value="Hello World" class="textInput" /> <button class="copy">Copy text</button> <script> document.querySelector(".copy").addEventListener("click", copyText); function copyText() { var copyText = document.querySelector(".textInput"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("The copied text is: " + copyText.value); } </script> </body> </html>
输出
这将产生以下输出 −
点击‘复制文本’按钮 −