我在我的html页面中声明了这个div:
<div class="ol-unselectable ol-layers" style="position: absolute; width: 100%; height: 100%; z-index: 0;">
</div>
在某些时候,上面显示的div元素中的样式更改为none:
<div class="ol-unselectable ol-layers" style="position: absolute; width: 100%; height: 100%; z-index: 0; display: none;">
</div>
什么时候向div元素添加显示内容:无;我需要解雇这一行:
alert("not displayed");
为此,我需要创建一个侦听器,当显示更改为无时,它将触发警报。
我的问题是如何使事件监听器监听div样式是否具有display: none
属性?
如果CSS中的更改是使用JavaScript完成的,则可以使用MutationObserver
来检测更改。每当目标元素发生DOM更改时,它将调用给定函数。
const target = document.querySelector('.ol-unselectable');
const observer = new MutationObserver(function(mutations, observer) {
for(let {type, target} of mutations) {
if (type === 'attributes' && target.style.display === 'none')
alert("not displayed")
}
})
observer.observe(target, {attributes: true})
target.addEventListener('click', () => target.style.display='none')
.ol-unselectable {
background: blue;
cursor: pointer;
}
<div class="wrapper">
<div class="ol-unselectable ol-layers" style="position: absolute; width: 50%; height: 50%; z-index: 0;">
</div>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句