我正在开发一个 Prestashop 站点项目,该项目具有特别繁琐的 megamenu 设置。
当MutationObserver
购物车覆盖打开时,它在将菜单推回方面做得很好,但是如果菜单被另一个 JavaScript 库动态拉入,该库被混淆,超出了任何救援范围,因此MutationObserver
每次都与节点取消链接,如果在页面加载后将任何内容添加到购物车中,则会导致所有内容都被错误地绘制。
当前MutationObserver
直接链接到主页容器对象 ( category
)。
// CREATE A MUTATION OBSERVER OBJECT TO MONITOR ANY STATE CHANGES ON THE JS NODE
let observer = new MutationObserver(blockCartOpened);
function blockCartOpened(mutationRecords) {
// PROCESS THE LIST OF MUTATION THAT HAVE OCCURED
mutationRecords.forEach (function (mutation) {
// GET THE MUTATION TARGET AND SEE IF THE DISPLAY STYLE ATTRIBUTE IS SET OR NOT
// AND REACT ACCORDINGLY
var target = $(mutation.target);
if(target.hasClass("cart_block")) {
if(target.css("display") == "block") {
$(".ets_mm_megamenu").css("z-index", "-1");
} else {
$(".ets_mm_megamenu").css("z-index", "2");
}
}
mutation.addedNodes.forEach(function(node) {
// Nothing to be here yet...
});
});
}
// SET THE TARGETNODE AS WELL AS THE SETTINGS FOR WHAT TO TRIGGER THE OBSERVER ON, IN THIS CASE
// TRIGGER THE OBSERVER ON ANY CHANGES TO THE STYLE ATTRIBURES OF THE NODE
var targetNodes = document.getElementById("category");
var observerOptions = {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["style"]
}
// SINCE THIS IS A CLASS, A EACH LOOP IS REQUIRED EVEN IF THERE IS ONLY ONE RESULT
observer.observe(targetNodes, observerOptions);
有没有办法监控父节点内创建的子节点的属性变化,或者这只是一个白日梦?