我正在使用特别古怪的megamenu设置处理Prestashop站点项目。
MutationObserver
在打开购物车叠加层时可以很好地将菜单推回,但是如果菜单是由另一个JavaScript库动态拉入的,而该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);
有没有一种方法可以监视父级内部已创建的子节点上的属性更改,或者这只是白日梦?
最后,我不必使用MutationObserver,因为事实证明该问题不适合这种解决方案。因此,我采取了最少保留的方法,即该解决方案虽然不够优雅,但却可以完美地起作用:
// BPK: CODE ADDITIONS
$(document).on("click", function(event) {
var target = $(".blockcart-header");
if(target.hasClass("open")) {
$(".ets_mm_megamenu").css("z-index", "-1");
} else {
$(".ets_mm_megamenu").css("z-index", "2");
}
});
$(document).on("click", ".blockcart-header a", function(event) {
var target = $(".blockcart-header");
if(target.hasClass("open")) {
$(".ets_mm_megamenu").css("z-index", "-1");
} else {
$(".ets_mm_megamenu").css("z-index", "2");
}
});
// END BPK
[使用文档范围的单击事件来监视“关闭”单击,并在购物车显示的触发按钮上单击事件,以确保为我解决了该问题。
课程:不要试图变得太复杂而无法解决问题...