javascript - 悬停时复制到剪贴板

标签 javascript dom-events copy-paste

我试图在鼠标悬停时将文本复制到剪贴板,并注意到它仅适用于点击 (document.body.addEventListener('click', copy, true);),但是当您尝试在悬停时触发复制不起作用 (document.body.addEventListener('mouseover', copy, true);)。我在玩这个 example并想知道为什么会这样。

最佳答案

document.execCommand 需要用户事件才能工作。它不会在悬停时起作用,但会在点击等(鼠标按下、鼠标弹起等)时起作用。

您可能仍想检查兼容性 (here)。引用this original answer和 ( this) jsFiddle。似乎浏览器现在确实始终如一地支持它,但您仍然需要确保您想要以表中的那些版本为目标。

$('.big').hover(function () {
    // will not work, no user action
  $('input').select();
    document.execCommand('copy');
});

$('.big').mousedown(function () {
    //works
  document.execCommand('copy');
});

Copy commands triggered from document.execCommand() will only affect the contents of the real clipboard if the event is dispatched from an event that is trusted and triggered by the user, or if the implementation is configured to allow this. How implementations can be configured to allow write access to the clipboard is outside the scope of this specification.

关于javascript - 悬停时复制到剪贴板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39389776/

相关文章:

excel - 如何禁用 Excel 在复制/粘贴后自动更改单元格引用?

JavaScript 日期操作

javascript - 如何在javascript函数中包含php文件?

javascript - 在ajax jquery中显示json响应,

javascript - 为什么在 Javascript 游戏中不触发 onkeyup 事件

javascript - 将 extjs drop 事件监听器放在 Controller 而不是 View 中

javascript - 从数组中删除相似的对象

javascript - 限制为每秒两次键盘输入

ios - 基本的 iPhone 粘贴板用法

javascript - 我的 JavaScript 复制到剪贴板代码不起作用