如何检测到textarea的任何更改? [英] How do I detect any change to a textarea?
问题描述
我目前已经将我的textarea绑定到一些似乎有效的事件。然而,问题是事件重叠并发生了几次火灾,从而使性能下降了太多。
I currently have bound my textarea to a couple of events which seems to work. However, the problem is that the events overlap and fire several times, which in turn reduces performance by a factor of too much.
我想做的是几乎抓住对文本区域进行任何更改:单击,粘贴,加密,键控,右键单击上下文菜单编辑(右键单击,剪切/删除/粘贴),拖放等。这必须跨浏览器工作,至少可以到IE8。当您使用箭头或类似方式在文本区域中移动插入符号时,事件必须触发(我处理基于插入位置的更改等等)。
What I want to do is pretty much catch any change to the textarea: clicking, paste, keyup, keydown, right click context menu editing (right click, cut/delete/paste), drag and drop, etc. This has to work cross-browser and atleast down to IE8. The events have to fire when you move the caret around in the textarea using arrowkeys or similar (I handle changes based on caret position, among other things).
我可以'不要使用任何重大延误。一旦你对textarea做了一些事情,事件就要触发并执行我立即有的代码。
I can't use any major delays. As soon as you do something with the textarea, the events have to fire and execute whatever code I have there immediately.
我目前正在使用jQuery来绑定事件,但是我只需要一个纯粹的JavaScript解决方案,只要它的工作原理是跨浏览器,然后执行所需的操作。
I am currently using jquery to bind the event, but I am fine with a pure javascript solution as long as it works cross browser and does what I want.
这是我目前使用的代码:
Here's the code I currently use:
var deadKeycodes = [16, 17, 18, 19, 20,
27, 33, 34, 35, 36,
38, 40, 44, //37 = left arrow and 39 = right arrow removed, it needs to trigger on those
45, 112, 113, 114, 115,
116, 117, 118, 119, 120,
121, 122, 123, 144, 145];
$(original).bind('propertychange keyup keydown input click', function(e) {
if (!Array.prototype.indexOf || deadKeycodes.indexOf(e.keyCode) == -1) { // prevent execution when pressing a 'dead' key
//do stuff here
}
});
提前感谢。如果有什么不清楚的问题,我会为你澄清一下:)
Thanks in advance. If anything is unclear just ask and I'll clarify it for you :)
推荐答案
你的原创是过分的。所有你需要的是输入
和 propertychange
事件。
Your original is overkill. All you need are the input
and propertychange
events.
2016更新
最初链接的页面现在已经消失了。这是一个稍微不太理想的快照:
The originally linked page has now disappeared. Here's a slightly suboptimal snapshot of it:
这是一个演示使用输入
事件的答案并返回到IE <= 8:
Here's an answer demonstrating using the input
event and falling back to propertychange
in IE <= 8:
propertychange .com / questions / 6488171 / catch-only-keypresses-that-change-input>只捕捉改变输入的按键?
Catch only keypresses that change input?
这篇关于如何检测到textarea的任何更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!