在 JavaScript 中拦截粘贴数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24540765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Intercept Paste data in JavaScript
提问by wibberding
I got the following code from Intercept paste event in Javascript.
我从Javascript 中的 Intercept paste event 中得到了以下代码。
I need to get it before it is pasted, otherwise i lose the "\n" characters i need to save.
我需要在粘贴之前获取它,否则我会丢失需要保存的“\n”字符。
It works great to intercept clipboard data for one element with an id. I need it to work on all input elements. When I try to use jQuery to get the input elements nothing.
拦截带有 id 的一个元素的剪贴板数据非常有效。我需要它处理所有输入元素。当我尝试使用 jQuery 获取输入元素时什么也没有。
Any help is appreciated.
任何帮助表示赞赏。
var paster = function () {
var myElement = document.getElementByTagName('pasteElement');
myElement.onpaste = function(e) {
var pastedText = undefined;
if (window.clipboardData && window.clipboardData.getData) { // IE
pastedText = window.clipboardData.getData('Text');
} else if (e.clipboardData && e.clipboardData.getData) {
pastedText = e.clipboardData.getData('text/plain');
}
processExcel(pastedText); // Process and handle text...
return false; // Prevent the default handler from running.
};
}
回答by nmaier
Just add a paste
event listener to the document.
只需paste
向文档添加一个事件侦听器即可。
document.addEventListener("paste", function (e) {
console.log(e.target.id);
var pastedText = undefined;
if (window.clipboardData && window.clipboardData.getData) { // IE
pastedText = window.clipboardData.getData('Text');
} else if (e.clipboardData && e.clipboardData.getData) {
pastedText = e.clipboardData.getData('text/plain');
}
e.preventDefault();
e.target.value = "You just pasted '" + pastedText + "'";
return false;
});
回答by Peter Smartt
What nmaiersaid, but you also need to check for the original event.
什么nmaier说,但你还需要检查原始事件。
document.addEventListener("paste", function (e) {
console.log(e.target.id);
var pastedText = undefined;
if (window.clipboardData && window.clipboardData.getData) { // IE
pastedText = window.clipboardData.getData('Text');
} else {
var clipboardData = (e.originalEvent || e).clipboardData;
if (clipboardData && clipboardData.getData) {
pastedText = clipboardData.getData('text/plain');
}
e.preventDefault();
e.target.value = "You just pasted '" + pastedText + "'";
return false;
}
});
Also, you should probably add the event listener just to the element, instead of the whole document.
此外,您可能应该仅将事件侦听器添加到元素,而不是整个文档。