JavaScript 如何复制文本到剪贴板
为了在JavaScript中将文本复制到剪贴板中,我们使用document.execCommand()方法。可以通过以下方法来实现。
方法:
- 将要复制的文本放入输入框中。
- 使用document.getElementById()方法来获取输入框的值。
- 使用element.select()方法来选择文本字段。
- 使用document.execCommand(“copy”)来复制文本。
- 使用element.value()方法来获取文本。
JavaScript代码如下:
function GeeksForGeeks() {
/* Get the text field */
let copyGfGText = document.getElementById("IdOfTextToCopy");
/* Select the text field */
copyGfGText.select();
/* Copy the text inside the text field */
document.execCommand("copy");
/* Use below command to access the
value of copied text */
console.log(copyGfGText.value);
}
注意: document.execCommand()方法在IE8及更早版本中不受支持。
示例: 在这个示例中,我们将应用上述方法。
<!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>
How to copy the text to the
clipboard in JavaScript ?
</title>
</head>
<body>
<h1 style="color:green;">
GeeksForGeeks
</h1>
<input type="text" value="GeeksForGeeks"
id="GfGInput">
<button onclick="GeeksForGeeks()">
Copy text
</button>
<p>
Click on the button to copy the text
from the text field.<br> Try to paste
the text (e.g. ctrl+v) afterwards in
a different window, to see the effect.
</p>
<p id="gfg"></p>
<script>
function GeeksForGeeks() {
let copyGfGText =
document.getElementById("GfGInput");
copyGfGText.select();
document.execCommand("copy");
document.getElementById("gfg")
.innerHTML = "Copied the text: "
+ copyGfGText.value;
}
</script>
</body>
</html>
输出:

极客教程