![](/img/trans.png)
[英]Is there a way to detect when a DOM node is about to be removed from the DOM?
[英]How to detect if a node is removed from the DOM and return the index position
我了解到您通過將目標元素綁定到DOMNodeRemoved
事件來檢查從DOM中刪除的元素。 后來我發現它已被棄用,並已被mutationObserver()
方法取代。 我一直在閱讀這個API,但似乎我無法返回從DOM中刪除的元素的索引位置 。
有人可以幫我用class="post-container"
返回元素的位置嗎?
JS:
// select the target node
var target =document.getElementById('post-line');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.removedNodes) {
//if the element removed has class='post-container' , then get the index position
console.log( mutation.removedNodes.index() );
}
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true,subtree:true ,removedNodes: NodeList[1]};
// pass in the target node, as well as the observer options
observer.observe(target, config);
// later, you can stop observing
//observer.disconnect();
HTML:
<div id="post-line">
<div class="post-container">
<div><span></span></div>
</div>
<div class="post-container">
<div><span></span></div>
</div>
<div class="post-container">
<div><span></span></div>
</div>
我發現用於跟蹤一次發生的許多變化的唯一方法是通過以相反的順序枚舉突變然后從這些重建的數組中獲取索引來重建每個修改目標的原始子數組。 這也解決了一個突變的報告的問題previousSibling
和nextSibling
可能已被包含在另一個同時突變修飾mutations
。
var mutationObserver = new MutationObserver((mutations) => {
// oldParents and oldChildren keep track of the modified targets
var oldParents = [], oldChildren = [];
// make a copy of all the modified targets' childNodes
for (var mutation of mutations) {
var target = mutation.target;
if (oldParents.indexOf(target) === -1) {
oldParents.push(target);
oldChildren.push(Array.from(target.childNodes));
}
}
// enumerate all mutations in reverse order
for (var mutation of mutations.slice().reverse()) {
// (optional) find the first modified ancestor
var target = mutation.target, ancestor = target, indexPath = [], found;
do {
found = false;
for (var i in oldChildren) {
var index = oldChildren[i].indexOf(ancestor);
if (index !== -1) {
indexPath.push(index);
ancestor = oldParents[i];
found = true;
}
}
} while (found);
// remove added children
var children = oldChildren[oldParents.indexOf(target)];
if (mutation.addedNodes.length > 0) {
// the index of the first added node, the other ones are consecutive
var index = children.indexOf(mutation.addedNodes[0]);
children.splice(index, mutation.addedNodes.length);
}
// add removed children back
if (mutation.removedNodes.length > 0) {
// the index of the first removed node, the other ones are consecutive
var index;
if (mutation.nextSibling) {
index = children.indexOf(mutation.nextSibling);
} else if (mutation.previousSibling) {
index = children.indexOf(mutation.previousSibling) + 1;
} else {
index = 0;
}
children.splice(index, 0, ...mutation.removedNodes);
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.