其实业务中还是会碰见这样的需求的,特别是一些框架内不,这个并不是很复杂,我们可以考虑如何去监听到 dom元素样式属性的变化就可以
很多童鞋可能对原生js的不够熟悉,现在大多数同学 只要会写简单的vue操作 就可以 做一些基础的前端工作了,然后就是查文档,其实更多的时间可以花在对自己js基础建设的
今天要说的这个就是一个js api
new MutationObserver
除了这个还有一个 面试会经常问的是 IntersectionObserver 监听dom元素进入可视化区域,用这个api完成图片的懒加载,但今天主角又不是它嘿嘿,
而且这个api兼容性也是不错的哦
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>div {display: none;height: 200px;border: 1px solid #f00;}</style>
</head><body><div></div><script>var div = document.querySelector('div')const config = { attributes: true }const observe = new MutationObserver((mutations, observer) => {for(let mutation of mutations){ if(mutation.type === "attributes") {console.log('dom is now visible')}}})observe.observe(div, config)setTimeout(() => {div.style.display = 'block'}, 3000)</script>
</body></html>
关注我 持续更新 前端知识。 也希望看到这篇博客的同学 多多关注基础js,大神不用接受这个意见