悬停时复制到剪贴板

Copy to clipboard on hover

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

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

您可能还想检查兼容性 (here). Refer to and (this) jsFiddle。似乎浏览器现在确实一直支持它,但您仍然需要确保要在 table.

中定位这些版本
$('.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.