-
Notifications
You must be signed in to change notification settings - Fork 39
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
MutationObserver是什么? #173
Labels
Comments
MutationObserver概览
|
MutationObserver构造器
callback接受MutationRecord和MutationObserver两个入参。MutationRecord描述的是变化;MutationObserver触发callback。 示例
callback functionfunction callback(mutationList, observer) {
mutationList.forEach((mutation) => {
switch (mutation.type) {
case 'childList':
// 关注mutation.addedNodes和mutation.removedNodes属性
break;
case 'attributes':
// 关注mutation.target, mutation.attributeName, mutation.oldValue
break;
}
})
} callback() 函数会在observer用observe()开始监视DOM时,指定的观察请求配置相匹配的更改时,将调用callback()函数。 创建并且启动observer下面的代码设置了整个观察进度。 var targetNode = document.querySelector("#someElement");
var observerOptions = {
childList: true,
attributes: true,
subtree: true, // 忽略或设置为false,只观察父节点的更改
}
var observer = new MutationObserver(callback);
observer.observe(targetNode, observerOptions);
|
MutationObserver实战自定义高德地图panel样式(与深度选择器效果相同的js方案)<style lang="scss">
// 隐藏跳转高德地图的按钮
/deep/ .amap-call {
display: none;
}
</style> 为什么要动态监听panel子节点?
不使用深度选择器的话,还有没有其他的方式去修改? 实现步骤
代码实现<div id="panel"></div> // 动态检测panel的amap-call节点
observePanelAmapCallNode() {
const callback = (mutationList, observer) => {
mutationList.forEach((mutation) => {
switch (mutation.type) {
case 'childList':
// 关注mutation.addedNodes和mutation.removedNodes属性
console.log(mutation, observer);
if (mutation.addedNodes[0].className === 'amap-call') {
mutation.addedNodes[0].style.display = 'none';
}
break;
default: {
console.log(mutation, observer);
}
}
});
};
const targetNode = document.querySelector('#panel');
const observerOptions = {
childList: true,
subtree: true,
};
this.panelAmapCallNodeObserver = new MutationObserver(callback);
this.panelAmapCallNodeObserver.observe(targetNode, observerOptions);
},
// 取消监听observer
disconnectObserver() {
this.panelAmapCallNodeObserver.disconnect();
}, mounted() {
this.observePanelAmapCallNode();
} beforeDestroy() {
this.disconnectObserver();
} MutationObserver成功! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: