我有一个在双击事件处理程序上调用的函数。我在dblclick事件上调用下面的函数,将目标文本作为参数文本复制。
copyToClipboard = function (texttocopy) {
'use strict';
var answer = confirm(`Do you want to copy into the clipbaord `);
if (answer == true) {
let input = document.createElement('textarea');
input.innerHTML = texttocopy;
document.body.appendChild(input);
input.select();
let result = document.execCommand('copy', false);
document.body.removeChild(input);
if (result) return;
else alert("Failed to copy to clipboard");
}
}如果我在2秒内按确认弹出窗口的Ok,我的代码是成功的,但如果我在5-10秒后按,它就失败了。我的理解是,document.exeCommand适用于生命周期较短的用户生成事件处理程序。但我想知道什么才是真正的“短暂事件”,有没有一种方法可以让我在编程上取得成功。
发布于 2021-04-28 15:15:39
正如你已经提到的:
如果您在用户操作的短期事件处理程序(例如,单击处理程序)中使用这些命令,则无需任何特殊权限即可使用这些命令。(source
您遇到的问题是您使用的是confirm。此对话框中断正常流程(它会暂停操作),这会破坏您对该事件处理程序的作用域的控制。
删除该confirm应该可以解决您的问题:
copyToClipboard = function (texttocopy) {
'use strict';
var answer = true; //confirm(`Do you want to copy into the clipbaord `);
if (answer == true) {
let input = document.createElement('textarea');
input.innerHTML = texttocopy;
document.body.appendChild(input);
input.select();
let result = document.execCommand('copy', false);
document.body.removeChild(input);
if (result) return;
else alert("Failed to copy to clipboard");
}
}
document.getElementById('copy')
.addEventListener('click', () => copyToClipboard(
'Copy this text to the clipboard!'));<button type="button" id="copy">Click me!</button>
https://stackoverflow.com/questions/67295401
复制相似问题