我有一个内容可编辑的 div,其中包含一些 html 元素。例如,假设我有:
<div contenteditable="true" id="myTextArea">
Some content, <div id="div1">content in div</div>,
and more <span id="span1">content</span></div>
当用户在 myTextArea 中编辑文本并删除一些 html 元素(通过粘贴新内容或只是退格文本)时,我希望每个 html 元素触发一个事件并告诉我它已被删除。关于如何做到这一点的任何想法?
最佳答案
你可以使用 MutationObserver
为了达成这个。要跟踪从 contenteditable
元素中删除的任何类型的节点,请观察以下示例
<div id="myTextArea" contenteditable="true">
<input value="input" />
<span contenteditable="false">span</span>
</div>
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
//console.log($(mutation.removedNodes)); // <<-- includes text nodes as well
$(mutation.removedNodes).each(function(value, index) {
if(this.nodeType === 1) {
console.log(this) // your removed html node
}
});
});
});
var config = { attributes: true, childList: true, characterData: true };
observer.observe($('#myTextArea')[0], config);
JSFiddle Link
关于javascript - 如何在 contenteditable 中删除 HTML 元素时触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13041726/