在我的JSP文本字段中,我希望知道用户是在输入数据还是粘贴数据。我该如何使用javascript来识别?
编辑:根据安迪的答案,我知道如何处理它,但仍然好奇那些人是如何编写onpaste事件的。
编辑:根据安迪的答案,我知道如何处理它,但仍然好奇那些人是如何编写onpaste事件的。
Safari、Chrome、Firefox和Internet Explorer都支持onpaste
事件(不确定Opera是否支持)。监听onpaste
事件,就可以捕获粘贴的内容。
<input type="text" id="myinput" onpaste="handlePaste(event);">
var myInput = document.getElementById("myInput");
if ("onpaste" in myInput) // onpaste event is supported
{
myInput.onpaste = function (e)
{
var event = e || window.event;
alert("User pasted");
}
}
// Check for mutation event support instead
else if(document.implementation.hasFeature('MutationEvents','2.0'))
{
/* You could handle the DOMAttrModified event here, checking
new value length vs old value length but it wouldn't be 100% reliable */
}
据我所知,Opera浏览器不支持onpaste
事件。您可以使用DOMAtrrModified
事件,但这会在脚本更改输入框的值时触发,因此您必须小心处理。不幸的是,我不熟悉突变事件,因此我不想通过编写我不确定的示例来搞砸这个答案。
统计按键次数,并确保与文本框中的内容匹配。粘贴的内容可能不完整,与文本框中的字符数量不一致。
我知道对于文本区域,你可以使用 onPaste
事件来捕获粘贴事件。
HTML:
<textarea id="textEditor" />
在JS中:
var editor = document.getElementById("textEditor");
if (isIE /* determine this yourself */) {
editor.onPaste = function() {
}
} else {
//Not IE
editor.onpaste = function() {
}
}
//The capitalisation of the onpaste (non-IE) and onPaste (IE) makes a difference.
onKeyDown
、onKeyUp
和 onKeyPress
事件。可能与 SO 相关的问题 IE onPaste event using javascript not HTML
你永远无法确定。即使拦截关键输入,用户可能使用上下文菜单使用鼠标粘贴。访问剪贴板(以比较输入和剪贴板内容)将不能按照您所需的方式进行,因为它是一个严格的用户操作。未经用户明确同意,您将无法以编程方式访问它(浏览器将显示确认消息)。