使用右键单击复制时复制命令不起作用

时间:2017-08-01 04:57:31

标签: javascript oncopy

我正在尝试捕获复制事件并使用一些信息更新剪贴板。以下是我正在尝试的,它工作正常,除非用户尝试使用右键单击复制 - >复制选项。这不仅不起作用,而且也不允许基本的复制操作。

<h1 onCopy="dosomething()">
blah1 lorem ispum eng auf
</h1>

<script type="text/javascript">
function dosomething() {

    var selection = window.getSelection().toString();
    var formattedSelection = selection.trim() + "-random";
    var textarea = document.createElement('textarea');
    console.log("f=", formattedSelection);
    textarea.textContent = formattedSelection;
    textarea.style.position = 'fixed';  // Prevent scrolling to bottom of page in MS Edge.
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');            
    document.body.removeChild(textarea);

};
</script>

有人可以帮我找到我在这里做错的事吗?在这里准备一个jsfiddle以便于调试 - https://jsfiddle.net/a74x41rk/

编辑 -

我使用setTimeout工作,但仍然不确定为什么。

setTimeout(function(){      
        document.execCommand('copy');
        document.body.removeChild(textarea);
      });     

更新小提琴 - https://jsfiddle.net/a74x41rk/1/

0 个答案:

没有答案
相关问题