使用Javascript / jQuery捕获对输入框内容的所有更改
我有一个带有输入框的页面,以及一个处理此输入框的值并生成一段文本的函数。我希望这个文本总是与输入框的内容相关,所以我用jQuery附加了几个事件处理程序来捕获任何更改:
I have a page with an input box, and a function that processes the value of this input box and produces piece of text. I want this text to always be up to date in relation to the contents of the input box, so I've attached a couple of event handlers to it with jQuery to catch any changes:
$('#input').bind('keyup cut paste', function(){...});
这在大多数情况下效果很好。只要用户以任何方式使用键盘修改内容,或右键单击以使用剪切或粘贴功能,文本就会立即更新。然而,有两个事件我仍然没有弄清楚如何捕获,如果它甚至可能这样做:
This works well in most cases. Whenever the user modifies the contents using the keyboard in any way, or right-clicks to use the cut or paste functions, the text is updated immediately. However, there are two events I still haven't figured out how catch, if it's even possible to do so:
- 当用户选择时文本和拖动它在输入框中的位置不同
- 当用户在右键单击上下文菜单中使用删除操作时
这两个当然可以通过绑定更改
事件来检测,但这种方法的问题在于它没有'直到输入框失去焦点为止。这些绑定的重点是在输入框的值发生变化时实时更新文本,因此更改
是不行的。
Both of these can of course be detected by binding the change
event, but the problem with that approach is that it doesn't fire until the input box loses focus. The whole point of these bindings is to have the text update in real-time as the value of the input box changes, so change
is no good.
英语是我的第二语言,所以我可能只是对我的谷歌搜索措辞不好,但到目前为止他们什么也没发现。在挖掘了几个相关的SO页面后,我还没有找到任何解决方案,所以我在这里问。是否有一个我不知道的事件绑定?如果没有,我可以采取不同的方法吗?或者使用普通的Javascript是不可能的?
English is my second language so I could simply be bad at wording my Google searches, but so far they've turned up nothing. I haven't found any solutions to this after digging through a couple of related SO pages either, so I'm asking here. Is there an event binding for this that I don't know of? If not, is there a different approach I could take? Or is this simply not possible with plain Javascript?
在非IE浏览器中,您可以处理输入
事件。
在IE中,您可以处理 propertychange
事件。
In non-IE browsers, you can handle the input
event.
In IE, you can handle the propertychange
event.
演示(适用于所有浏览器)
Demo (works in all browsers)