将文本或图像粘贴到DIV(如输入)的方法是单击该DIV并执行粘贴注释,通常是CTRL + V.
现在,我的问题是,即使没有选择DIV,Javascript是否可以将文本或图像粘贴到DIV甚至是DIV(或输入)?
更新
<div contenteditable="true" id="pasteCapture" style="height: 100px; width: 100px; " onpaste='handlepaste(this, event)'></div>
<script>
function getfocus(){
document.getElementById('pasteCapture').focus()
}
</script>
到目前为止,这就是我所做的。当选择div并进行粘贴时,没问题。但是,我的要求是这个DIV应该得到粘贴项甚至它未在页面上选中。
原因是我会隐藏这个div。
答案 0 :(得分:1)
如果我理解正确,您想拦截粘贴事件并将粘贴重定向到隐藏的div。我可以做一些:
HTML 的
Paste Stuff Here: <input id='pasteCapture' type='text'></input>
<div contenteditable="true" id="pasteRedirect" style="height: 100px; width: 100px; " >
</div>
<button
onclick=" document.getElementById('pasteRedirect').style.display = 'block';"
>Show Div</button>
SCRIPT
function handlePaste(e) {
document.getElementById('pasteRedirect').style.display = 'block';
document.getElementById('pasteRedirect').focus();
e.srcElement = document.getElementById("pasteCapture");
setTimeout( function() {
document.getElementById('pasteRedirect').style.display = 'none';
}, 0 );
}
document.getElementById("pasteCapture").addEventListener("paste", handlePaste, false);
(Fiddle)
如果您粘贴到输入框中,它会被捕获并重定向到DIV。我试图让它在整个页面上工作,或者在容器div中工作,但它没有 - 看起来只有一些元素会触发粘贴事件。
同样,当隐藏DIV时它不起作用,因此它需要取消隐藏DIV,然后在粘贴完成后使用超时来重新隐藏它。
我不确定你是否可以为你想做的事情做好工作。