比如想實現點擊列表彈出篩選器,點擊其他任意地方關閉篩選器,如圖
該篩選器class名
1 $(document).click(function () { 2 $(".subMenu").hide(); 3 }); 4 $(".subMenu").on("click", function (event) { 5 //取消事件冒泡 6 var e = arguments.callee.caller.arguments[0] || event; //若省略此句,下面的e改為event,IE運行可以,但是其他瀏覽器就不兼容 7 if (e && e.stopPropagation) { 8 // this code is for Mozilla and Opera 9 e.stopPropagation(); 10 } else if (window.event) { 11 // this code is for IE 12 window.event.cancelBubble = true; 13 } 14 });
首先點擊document任意位置隱藏該元素,然后給該元素綁定click事件,阻止冒泡到該元素,則可以順利實現需求。