I am trying to simulate the (not existing) change event for a content开发者_如何学运维Editable
element (but I guess it is the same problem for an input element). Unfortunately I don't know how to fetch the event when the user selected some text and chose "Delete" from the context menu in the browser.
Any suggestions how I could get that?
Revised answer, 8 June 2012
What you want is the HTML5 input
event. However, this currently only works in WebKit for contenteditable
elements but hopefully will be implemented in other browsers too: Firefox 14 will apparently have it. It's already implemented in all major browsers for text inputs and textareas.
Demo: http://jsfiddle.net/timdown/5e5E5/1/
HTML:
<div id="test" contenteditable="true">...</div>
JS:
var editableDiv = document.getElementById("test");
editableDiv.addEventListener("input", function(evt) {
alert("Editable content changed");
}, false);
For a cross-browser solution, you can use some of the various DOM mutation events (also see MDN) that will be fired. I'd suggest DOMCharacterDataModified
and possibly DOMNodeRemoved
will be the useful ones for this purpose.
Note that these events do not exist in IE <= 8. Furthermore, these events are deprecated in favour of DOM4 Mutation Observers. However, at the time of writing (June 2012), only very recent WebKit browsers support this, so for the short to medium term we're stuck with mutation events as a fallback at minimum.
editableDiv.addEventListener("DOMCharacterDataModified", function(evt) {
if (evt.newValue.length < evt.prevValue.length) {
alert("Characters deleted");
}
}, false);
精彩评论