【问题标题】:can't use document.execCommand('copy') with input type file不能将 document.execCommand('copy') 与输入类型文件一起使用
【发布时间】:2016-01-30 08:22:32
【问题描述】:

无法将 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>

如果我在 return 语句之前的 if 块中的 setTimeout(call,100) 之后添加一个 alert()
正在复制文本。
在 chrome、opera 和 firefox 上尝试过,每个浏览器都以相同的方式响应。
我正在使用上述结构复制用户打开的文件的 base64 编码文本。

【问题讨论】:

    标签: javascript html file copy execcommand


    【解决方案1】:

    大多数浏览器只会以这种方式将文本从 Javascript 复制到剪贴板,该 Javascript 是直接从真实用户事件(如点击或按键)而不是 setTimeout() 启动的。因此,如果您的代码采用setTimeout() 路径,那么将文本复制到剪贴板很可能无法正常工作。您不能只制造按键事件 - 此限制的全部意义在于要求一个真实的用户事件,而不是由代码制造的事件。

    如果您有兴趣,这里有一个经过测试的函数,可以将文本复制到 this answer 中的剪贴板。它与任何其他代码具有相同的限制 - 它必须从由真实用户事件调用的 Javascript 启动,它适用于现代版本的 Chrome、Firefox 和 IE,但不适用于 Safari。

    【讨论】:

      猜你喜欢
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 2010-11-25
      • 1970-01-01
      • 1970-01-01
      • 2019-11-14
      • 2022-09-30
      • 1970-01-01
      相关资源
      最近更新 更多