获取已编辑元素的删除事件 [英] Get delete event of edited element
问题描述
我正在尝试模拟contentEditable元素的(不存在的)更改事件(但我想这对输入元素来说是同样的问题)。不幸的是,当用户选择了一些文本并从浏览器的上下文菜单中选择删除时,我不知道如何获取事件。
I am trying to simulate the (not existing) change event for a contentEditable 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?
推荐答案
修订回答,2012年6月8日
你想要的是 HTML5 输入
事件。但是,这目前只能在WebKit中用于 contenteditable
元素,但希望也可以在其他浏览器中实现: Firefox 14显然会拥有它。 已在所有主要浏览器中实现了文本输入和文本替换。
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.
演示: 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);
对于跨浏览器解决方案,您可以使用各种 DOM突变事件(另见 MDN )。我建议 DOMCharacterDataModified
并且可能 DOMNodeRemoved
将是有用的。
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.
请注意,这些事件在IE< = 8中不存在。此外,这些事件已被弃用,有利于 DOM4 Mutation Observers 。然而,在撰写本文时(2012年6月),只有非常近期的WebKit浏览器才支持这一点,因此对于中短期内我们会将突变事件作为最低限度的回退。
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);
这篇关于获取已编辑元素的删除事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!