如何在 Chrome 和 Firefox 中秘密複製到剪貼簿 JavaScript 函式?


在本文中,我們將嘗試如何將 JavaScript 函式秘密複製到剪貼簿。

我們使用 copytext() 方法秘密將 JavaScript 函式複製到剪貼簿。這些函式也適用於 JavaScript 控制檯。為了更好地理解,讓我們逐一檢視示例。

示例

以下是我們使用 copyText() 方法透過 JavaScript 函式複製文字到剪貼簿的示例程式。

<!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"> </head> <body> <input type="text" value="Copy me!" id="myInput"> <button onclick="copyText()">Copy text</button> <script> function copyText() { var copyText = document.getElementById("myInput"); copyText.select(); document.execCommand("copy"); // alert("Copied the text: " + copyText.value); } </script> </body> </html>

新增警報

我們還可以使用 alert() 方法向 copytext() 方法複製的文字新增一個警報。

示例

以下是將文字複製到剪貼簿並會在複製文字後顯示警報的示例程式。

<!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"> </head> <body> <input type="text" value="Copy me!" id="myInput"> <button onclick="copyText()">Copy text</button> <script> function copyText() { var copyText = document.getElementById("myInput"); copyText.select(); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } </script> </body> </html>

已複製的文字警報顯示為 -

示例

以下是使用 copyClipboard() 函式將文字複製到剪貼簿的示例程式 -

<!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"> </head> <body> <input type="text" value="Text" id="input"> <button onclick="copyClipboard()">Copy text Here!</button> <script> function copyClipboard() { var sampleText = document.getElementById("input"); sampleText.select(); sampleText.setSelectionRange(0, 99999) document.execCommand("copy"); alert("Copied the text: " + sampleText.value); document.write("Copied Text here:", sampleText.value); } </script> </body> </html>

更新時間:18-Nov-2022

982 人次瀏覽

開啟你的職業生涯

完成課程認證

開始
廣告
© . All rights reserved.