简体   繁体   English

不能对输入类型文件使用document.execCommand('copy')

[英]can't use document.execCommand('copy') with input type file

can't copy the content of textarea to clipboard using the code below. 无法使用以下代码将textarea的内容复制到剪贴板。



    <script>
    function copyText()
    {
    document.getElementById('in').click();
    call();
    }
    function call()
    {
    if(getComputedStyle(document.getElementById('butt')).opacity>0.5)
    {setTimeout(call,100);return;}

    var ta=window.document.createElement("textarea");
    window.document.body.appendChild(ta);
    ta.value="this text should be in clipboard";
    ta.focus();
    ta.selectionStart=0;
    ta.selectionEnd=ta.value.length;
    ta.addEventListener('keypress', function(){window.document.execCommand('copy');});
    var event = new Event('keypress');
    ta.dispatchEvent(event) ;
    }
    </script>
    <button id='butt' onClick='copyText()'>copy text</button>
    <input id='in' type='file' style='display:none;'/>
    <style>
    #butt
    {opacity:0.5;}
    #butt:hover
    {opacity:1;}
    </style>

while if i add an alert() after the setTimeout(call,100) in the if block before return statement. 而如果我在return语句之前的if块中的setTimeout(call,100)之后添加alert()
Text is being copied. 文本正在被复制。
tried it on chrome,opera and firefox every browser responded the same way. 在chrome,opera和firefox上进行了尝试,每个浏览器的响应方式都相同。
I am using the above structure to copy the base64 encoded text of the file that user opened. 我正在使用上述结构来复制用户打开的文件的base64编码文本。

Most browsers will only copy text to the clipboard in this way from Javascript that was directly initiated from a real user event (like a click or a key) and not from a setTimeout() . 大多数浏览器只会以这种方式从直接从真实用户事件(如单击或按键)而不是从setTimeout()启动的Javascript将文本复制到剪贴板。 So, if your code takes the setTimeout() path, then it is likely that the copying of the text to the clipboard will not work. 因此,如果您的代码采用setTimeout()路径,则可能无法将文本复制到剪贴板。 You can't just manufacture the keypress event - the whole point of this restriction is to require a real user event, not one manufactured by code. 您不能只制造按键事件-此限制的全部要点是需要一个真实的用户事件,而不是由代码制造的事件。

In case you're interested, here's a tested function to copy text to the clipboard in this answer . 如果您有兴趣,这里有一个经过测试的功能,可以在此答案中将文本复制到剪贴板。 It has the same restrictions as any other code - it must be initiated from Javascript that is called by a real user event and it works in modern versions of Chrome, Firefox and IE, but not in Safari. 它具有与任何其他代码相同的限制-必须从由实际用户事件调用的Javascript启动,并且它可以在现代版本的Chrome,Firefox和IE中使用,但不能在Safari中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM