作者:Vincy。最后修改于2022年9月9日。
这个JavaScript的例子脚本是将文本复制到系统剪贴板。我在本教程中介绍了三种不同的方法。
- 通过ClipBoard API。
- 使用document.executeCommand(不推荐)。
- 通过用户同意。
这个JS快速示例使用第一种也是最好的方法来复制文本区域的内容到剪贴板。
快速例子
var contentToCopy = document.getElementById(text_to_copy).value;
navigator.clipboard.writeText(contentToCopy).then(function() {
console.log('Copied to clipboard with async.');
}, function(err) {
console.error('Unable to copy with async ', err);
});
HTML textarea元素的内容是由JS脚本复制的。
- 使用剪贴板API
下面的HTML脚本给出了一个带有文本区和一个按钮的界面来触发复制动作。
点击按钮后,调用JavaScript*copyToClipBoard()*函数。这个函数将文本区的内容移动到剪贴板上。
index.html
<html>
<head>
<title>JavaScript Copy Text to Clipboard</title>
<script src="copy-clipboard-async.js"></script>
<script src="https://code.jquery.com/jquery-3.6.1.min.js"
integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ="
crossorigin="anonymous"></script>
<link rel='stylesheet' href='style.css' type='text/css' />
<link rel='stylesheet' href='form.css' type='text/css' />
</head>
<body>
<div class="phppot-container">
<h1>JavaScript Copy Text to Clipboard</h1>
<div class="row">
<div class="message-input">
<label for="message-input">Message: </label>
<textarea id="message-input" rows="15"
name="message-input" class="message-input"></textarea>
</div>
</div>
<div class="row">
<button onclick="copyToClipboard('message-input')"
type="button">Copy to clipboard</button>
</div>
<div class="row">
<div id="copied"></div>
</div>
</div>
</body>
</html>
这个JS脚本通过调用clipboard.writeText()将文本写到剪贴板上。它通过提供一个通过ClipBoard API复制内容的接口来增强快速示例。
copy-clipboard-async.js
/**
* to copy to the clipboard using the Clipboard API
*
* @param element
* @returns
*/
function copyToClipboard(element) {
var contentToCopy = document.getElementById(element).value;
navigator.clipboard.writeText(contentToCopy).then(function() {
console.log('Copied to clipboard with async.');
}, function(err) {
console.error('Unable to copy with async ', err);
});
}
- document.execCommand
这个方法被广泛用于通过调用executeCommand("copy")来复制内容。它已被废弃,但仍被许多浏览器支持。
它动态地将textarea元素附加到HTML正文中,并使用JavaScript选择其内容。然后executeCommand()函数的调用会触发复制动作。
copy-clipboard-execcommand.js
/**
* to copy to the clipboard using the document.execCommand
*
* @param element
* @returns
*/
function copyToClipboard(element) {
var contentToCopy = document.getElementById(element).value;
var temp = $("
- 按用户复制
这是将内容复制到剪贴板的最安全方法。这不使用JavaScript的任何本机函数,可以更多地描述为一个过程。它提示用户确认将所选内容复制到剪贴板。
<html>
<head>
<title>JavaScript Copy Text to Clipboard</title>
</head>
<body>
<!-- In this style, we present the control to the end user to copy. -->
<!-- Text to be copied is shown to the user and he uses the built-in browser's feature and copies to the clipboard. -->
<!-- If this is possible to use in your use case, then this is the safest method. -->
<button id="copy-btn"
onclick="copyToClipboard(document.getElementById('copy-btn').innerHTML)">Text
to copy.</button>
<script>
function copyToClipboard(text) {
window.prompt("Press Ctrl+C to copy to clipboard.",
text);
}
</script>
</body>
</html>