1 遮罩层,有一个遮罩层,盖住其他地方,然后只有目标div可以点击,点击遮罩层就可以隐藏;
2.body上绑定事件,关闭,组件销毁前把事件移除。
<div id="badge" @click="handleClick($event)">设置备注及标签</div>
methods: {handleBodyClick(){// 关闭// dom为上面的目标·div区域let dom = document.getElementById('badge')if (dom) {if (!dom.contains(e.target)) {this.messageShow = false}}}},mounted(){this.$nextTick(() => {document.querySelector('body').addEventListener('click', this.handleBodyClick);})},beforeDestroy(){document.querySelector('body').removeEventListener('click', this.handleBodyClick);}
3.监听事件
<!DOCTYPE HTML><html><head><meta charset="utf-8"><title>js实现的点击div区域外隐藏div区域</title> <style type="text/css"> #myDiv{ border:1px solid #000000; width:200px; height:100px; background:#FF0000;} </style> </head> <body> <div id="myDiv"></div></body><script type="text/javascript">console.log('1111111111')var myDiv = document.getElementById("myDiv");document.addEventListener("click",function(){console.log('5555')myDiv.style.display="none";});myDiv.addEventListener("click",function(badge){console.log('6666', badge)event=event||window.event;event.stopPropagation();});</script></html>