I'd suggest attaching listeners to key events fired by the editable element, though you need to be aware that keydown
and keypress
events are fired before the content itself is changed.
(我建议将侦听器附加到由editable元素触发的按键事件上,尽??管您需要知道在更改内容本身之前会触发keydown
和keypress
事件。)
This won't cover every possible means of changing the content: the user can also use cut, copy and paste from the Edit or context browser menus, so you may want to handle the cut
copy
and paste
events too.(这不会涵盖更改内容的所有可能方法:用户还可以从“编辑”或上下文浏览器菜单中使用剪切,复制和粘贴,因此您可能也想处理cut
copy
和paste
事件。)
Also, the user can drop text or other content, so there are more events there ( mouseup
, for example).(同样,用户可以放置文本或其他内容,因此在那里有更多事件(例如mouseup
)。)
You may want to poll the element's contents as a fallback.(您可能希望轮询元素的内容作为后备。)
UPDATE 29 October 2014
(2014年10月29日更新)
The HTML5 input
event is the answer in the long term.
(从长远来看, HTML5 input
事件就是答案。)
At the time of writing, it is supported for contenteditable
elements in current Mozilla (from Firefox 14) and WebKit/Blink browsers, but not IE.(在撰写本文时,当前Mozilla(来自Firefox 14)和WebKit / Blink浏览器中的contenteditable
元素均支持该功能,但IE不支持。)
Demo:
(演示:)
document.getElementById("editor").addEventListener("input", function() { console.log("input event fired"); }, false);
<div contenteditable="true" id="editor">Please type something in here</div>
Demo: http://jsfiddle.net/ch6yn/2691/
(演示: http : //jsfiddle.net/ch6yn/2691/)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…