不能在输入类型文件中使用document.execCommand('copy') [英] can't use document.execCommand('copy') with input type file
问题描述
无法将textarea的内容复制到剪贴板 使用下面的代码.
can't copy the content of textarea to clipboard using the code below.
<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编码文本.
while if i add an alert()
after the setTimeout(call,100)
in the if block before return statement.
Text is being copied.
tried it on chrome,opera and firefox every browser responded the same way.
I am using the above structure to copy the base64 encoded text of the file that user opened.
推荐答案
大多数浏览器只会以这种方式将文本从真实用户事件(如单击或按键)中直接启动的Javascript复制到剪贴板,而不会来自setTimeout()
.因此,如果您的代码采用setTimeout()
路径,则可能无法将文本复制到剪贴板.您不能只制造按键事件-此限制的全部要点是需要一个真实的用户事件,而不是由代码制造的事件.
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()
. So, if your code takes the setTimeout()
path, then it is likely that the copying of the text to the clipboard will not work. 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.
这篇关于不能在输入类型文件中使用document.execCommand('copy')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!