我想在弹出模式对话框时从元素中删除类,但是当我在线搜索时,我发现DOMNodeInserted,并且一直有效,直到上线并出现DOMNodeInserted错误为止不推荐使用。 我不断出现的错误enter image description here
下面的代码可以使用,但已被弃用。
$(document).on('DOMNodeInserted', function(e) {
if ( $("body").hasClass('modal-open') ) {
$(".hide-search").hide();
// $(".nav-menu").addClass("border-0");
} else if ($("body").hasClass('modal-open') === false){
$(".hide-search").show();
// $(".nav-menu").removeClass("border-0");
}
});
我想实施新代码,但我不知道该怎么做。
let body = document.querySelector('body');
let observer = new MutationObserver(mutationRecords => {
console.log(mutationRecords); // console.log(the changes)
// observe everything except attributes
observer.observe(body, {
childList: true, // observe direct children
subtree: true, // and lower descendants too
characterDataOldValue: true // pass old data to callback
});
});
}
}
class
属性,没有别的了,因此不需要非常昂贵的subtree:true
。class
可能包含其他内容,因此您需要忽略无关的更改new MutationObserver((mutations, observer) => {
const oldState = mutations[0].oldValue.split(/\s+/).includes('modal-open');
const newState = document.body.classList.contains('modal-open');
if (oldState === newState) return;
if (newState) {
$('.hide-search').hide();
} else {
$('.hide-search').show();
}
}).observe(document.body, {
attributes: true,
attributeFilter: ['class'],
attributeOldValue: true,
});