![](/img/trans.png)
[英]Fire event when caret enters span element in contenteditable div
[英]How to fire an event when HTML element gets deleted in contenteditable
我有一個內容可編輯的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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.