经常碰到这样的问题。可能会走偏。
正确的做法其实就是在window的mouseup中书写事件。而且该事件必须是setTimeout中。
以下是vue的demo
<template> <div> <ul id="nav"> <li v-for="(item,index) in items" @click="showNav($event,index)"> {{item.title}} <ul v-if="currentIndex === index" > <li v-for="c in item.children" @click="go">{{ c }}</li> </ul> </li> </ul> </div> </template> <script> export default { data () { return { items : [ {title:"首页"}, {title:"渠道质量",children:["渠道质量1","渠道质量2"]}, {title:"渠道结算"}, ], currentIndex : -1 } }, methods:{ showNav (el,index) { this.currentIndex = index; }, go () { window.open("http://www.baidu.com"); } }, created () { var self = this; window.addEventListener("mouseup",function(){ if(self.currentIndex != -1) { setTimeout(() => { self.currentIndex = -1}, 0) } }) } } </script>
2、其实有更简单的思路
// 点击屏幕任何角落,隐藏$ul
$(document).on("click", function(e){ $ul.hide(); });
上面可能需要扩展:监听e.target的内容来做逻辑