【发布时间】: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