我如何知道用户正在打字或粘贴?
在我的 JSP 的文本字段中,我希望知道用户是在输入数据还是只是粘贴。 我如何使用 javascript 来识别它?
编辑:根据安迪的回答,我知道如何去做,但仍然好奇那些人是如何编写 onpaste 事件的。
In text fields of my JSP, I wish to know whether user is typing in the data or just pasting.
How can I identify this using javascript ?
EDIT: As per Andy's answer I know how I can go about it, but still curios how those guys wrote onpaste event.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Safari、Chrome、Firefox 和 Internet Explorer 都支持
onpaste
事件(不确定 Opera 是否支持)。锁定onpaste
事件,您将能够在粘贴内容时捕获该事件。Writing this is simple enough. Add the event handler to your input using html:
或 JavaScript-DOM:
据我所知,Opera 不支持
onpaste
事件。您可以使用 DOMAtrrModified 事件,但即使脚本更改输入框的值,该事件也会触发,因此您必须小心处理。不幸的是,我不熟悉突变事件,所以我不想通过编写一个我不自信的例子来搞乱这个答案。Safari, Chrome, Firefox and Internet Explorer all support the
onpaste
event (not sure about Opera). Latch onto theonpaste
event and you will be able to catch whenever something is pasted.Writing this is simple enough. Add the event handler to your input using html:
or JavaScript-DOM:
From what I've read, Opera does not support the
onpaste
event. You could use theDOMAtrrModified
event, but this would fire even when scripts change the value of the input box so you have to be careful with it. Unfortunately, I'm not familiar with mutation events so I wouldn't like to mess this answer up by writing an example that I wouldn't be confident of.计算按键次数并确保其与文本框中的内容匹配,粘贴不会包含文本框中完整的字符数。
Count the key presses and make sure it matches whats in the text box a paste will not have complete number of characters as is in the text box.
你永远不会确切地知道。即使在拦截按键输入时,用户也可能使用上下文菜单来使用鼠标进行粘贴。访问剪贴板(将输入与剪贴板内容进行比较)将无法按您想要的方式工作,因为它是严格的仅限用户操作。未经用户明确同意,您无法以编程方式访问(浏览器将显示确认消息)。
You will never know for sure. Even when intercepting key input, the use may have used the context menu to paste using the mouse. Accessing the clipboard (to compare the input with the clipboard contents) will not work the way you want because it is a strict user-only operation. You are not able to access is programmatically without the explicit consent of the user (the browser will show a confirmation message).
我知道对于文本区域,您可以使用
onPaste
事件捕获粘贴事件。HTML:
在 JS 中:
对于输入,有
onKeyDown
、onKeyUp
、onKeyPress
事件。希望这有帮助。
可能与SO相关的问题 IE onPaste事件不使用javascript HTML
I know for textarea you can capture on paste event using the
onPaste
event.HTML:
In JS:
As for typing, there's
onKeyDown
,onKeyUp
,onKeyPress
events.Hope this helps.
Possible SO-related question IE onPaste event using javascript not HTML