web应用程序如何检测粘贴事件并检索要粘贴的数据?
我想在文本粘贴到富文本编辑器之前删除HTML内容。
在粘贴后清理文本是有效的,但问题是所有以前的格式都会丢失。例如,我可以在编辑器中编写一个句子并将其加粗,但当我粘贴新文本时,所有格式都会丢失。我只想清除粘贴的文本,并保留以前的任何格式不变。
理想情况下,解决方案应该可以跨所有现代浏览器(例如,MSIE、Gecko、Chrome和Safari)工作。
注意,MSIE有clipboardData.getData(),但我找不到其他浏览器的类似功能。
现场演示
在Chrome / FF / IE11上测试
有一个Chrome/IE的烦恼是这些浏览器为每一行添加<div>元素。这里有一篇关于这个的文章,它可以通过设置contentteditable元素为display:inline-block来修复
选择一些突出显示的HTML并粘贴在这里:
function onPaste(e){
var content;
e.preventDefault();
if( e.clipboardData ){
content = e.clipboardData.getData('text/plain');
document.execCommand('insertText', false, content);
return false;
}
else if( window.clipboardData ){
content = window.clipboardData.getData('Text');
if (window.getSelection)
window.getSelection().getRangeAt(0).insertNode( document.createTextNode(content) );
}
}
/////// EVENT BINDING /////////
document.querySelector('[contenteditable]').addEventListener('paste', onPaste);
[contenteditable]{
/* chroem bug: https://stackoverflow.com/a/24689420/104380 */
display:inline-block;
width: calc(100% - 40px);
min-height:120px;
margin:10px;
padding:10px;
border:1px dashed green;
}
/*
mark HTML inside the "contenteditable"
(Shouldn't be any OFC!)'
*/
[contenteditable] *{
background-color:red;
}
<div contenteditable></div>
当用户通过浏览器的用户界面发起“粘贴”操作时,粘贴事件将被触发。
HTML
<div class="source" contenteditable="true">Try copying text from this box...</div>
<div class="target" contenteditable="true">...and pasting it into this one</div>
JavaScript
const target = document.querySelector('div.target');
target.addEventListener('paste', (event) => {
let paste = (event.clipboardData || window.clipboardData).getData('text');
paste = paste.toUpperCase();
const selection = window.getSelection();
if (!selection.rangeCount) return false;
selection.deleteFromDocument();
selection.getRangeAt(0).insertNode(document.createTextNode(paste));
event.preventDefault();
});
知道更多
你可以这样做:
使用这个jQuery插件的前后粘贴事件:
$.fn.pasteEvents = function( delay ) {
if (delay == undefined) delay = 20;
return $(this).each(function() {
var $el = $(this);
$el.on("paste", function() {
$el.trigger("prepaste");
setTimeout(function() { $el.trigger("postpaste"); }, delay);
});
});
};
现在你可以使用这个插件;:
$('#txt').on("prepaste", function() {
$(this).find("*").each(function(){
var tmp=new Date.getTime();
$(this).data("uid",tmp);
});
}).pasteEvents();
$('#txt').on("postpaste", function() {
$(this).find("*").each(function(){
if(!$(this).data("uid")){
$(this).removeClass();
$(this).removeAttr("style id");
}
});
}).pasteEvents();
解释
首先将所有现有元素的uid设置为data属性。
然后比较所有节点的POST PASTE事件。因此,通过比较,您可以识别新插入的元素,因为它们将有uid,然后只需从新创建的元素中删除style/class/id属性,以便您可以保留旧的格式。
写完这篇文章后,情况发生了变化:现在Firefox在版本22中添加了支持,所有主流浏览器现在都支持在粘贴事件中访问剪贴板数据。请看Nico Burns的回答。
在过去,这在跨浏览器的方式中通常是不可能的。最理想的情况是能够通过paste事件获取粘贴的内容,这在最近的浏览器中是可能的,但在一些较老的浏览器中是不可能的(特别是Firefox < 22)。
当你需要支持旧的浏览器时,你可以做的是相当复杂的和一点hack,可以在Firefox 2+, IE 5.5+和WebKit浏览器(如Safari或Chrome)中工作。TinyMCE和CKEditor的最新版本都使用了这种技术:
Detect a ctrl-v / shift-ins event using a keypress event handler
In that handler, save the current user selection, add a textarea element off-screen (say at left -1000px) to the document, turn designMode off and call focus() on the textarea, thus moving the caret and effectively redirecting the paste
Set a very brief timer (say 1 millisecond) in the event handler to call another function that stores the textarea value, removes the textarea from the document, turns designMode back on, restores the user selection and pastes the text in.
请注意,这将只适用于键盘粘贴事件,而不是粘贴上下文或编辑菜单。当粘贴事件触发时,将插入符号重定向到文本区域就太晚了(至少在某些浏览器中是这样)。
在不太可能的情况下,您需要支持Firefox 2,请注意您需要将文本区域放置在父文档中,而不是在该浏览器中的所见即所得编辑器iframe的文档中。