javascript - 使用 jQuery 复制到剪贴板(来自 html 标签)
问题描述
解决方案
与浏览器中的其他一些操作(如打开新窗口)一样,复制到剪贴板只能通过特定的用户操作(如鼠标单击)完成。例如,它不能通过计时器来完成。
这是一个代码示例:
document.getElementById("copyButton").addEventListener("click", function() {
copyToClipboard(document.getElementById("copyTarget"));
});
function copyToClipboard(elem) {
// create hidden text element, if it doesn't already exist
var targetId = "_hiddenCopyText_";
var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
var origSelectionStart, origSelectionEnd;
if (isInput) {
// can just use the original source element for the selection and copy
target = elem;
origSelectionStart = elem.selectionStart;
origSelectionEnd = elem.selectionEnd;
} else {
// must use a temporary form element for the selection and copy
target = document.getElementById(targetId);
if (!target) {
var target = document.createElement("textarea");
target.style.position = "absolute";
target.style.left = "-9999px";
target.style.top = "0";
target.id = targetId;
document.body.appendChild(target);
}
target.textContent = elem.textContent;
}
// select the content
var currentFocus = document.activeElement;
target.focus();
target.setSelectionRange(0, target.value.length);
// copy the selection
var succeed;
try {
succeed = document.execCommand("copy");
} catch(e) {
succeed = false;
}
// restore original focus
if (currentFocus && typeof currentFocus.focus === "function") {
currentFocus.focus();
}
if (isInput) {
// restore prior selection
elem.setSelectionRange(origSelectionStart, origSelectionEnd);
} else {
// clear temporary content
target.textContent = "";
}
return succeed;
}
input {
width: 400px;
}
<input type="text" id="copyTarget" value="Text to Copy"> <button id="copyButton">Copy</button><br><br>
<input type="text" placeholder="Click here and press Ctrl-V to see clipboard contents">
推荐阅读
- java - 将事务添加到数据库的问题:通过反射持久属性 [main.Emails#id] 访问字段 [private long main.Emails.id] 时出错
- vb.net - 我使用绑定源在数据库的文本框中显示数据,我可以知道如何格式化文本框中显示的日期和时间吗?
- java - 未按计数评估中间流操作
- django-rest-framework - 将文件附加到使用 django-rest-framework 和 sendgrid 发送的电子邮件
- go - `go tool pprof` - 使用 go 模块时如何指定源?
- apache-spark - PairRDD 比非 Pair RDD 快吗?
- puppeteer - 使用 Puppeteer page.evaluate() 时得到不同的结果
- google-cloud-platform - 创建 VM 的副本
- android - 使用共享首选项保存列表时遇到问题(仍需要帮助)
- unit-testing - 如何在 Dart 或 Flutter 中模拟静态 getter 的返回值?