js点击页面其余地方如何隐藏div元素菜单

web页面经常使用的一个需求,写下拉菜单是咱们每每不是用select_option,而是自定义一个元素列出选项来知足需求,当咱们点击按钮出现菜单,css

点击按钮或菜单之外页面空白地方隐藏该菜单,这里提供一种简单有效的方法仅供参考:web

document.onclick = function(e) {        
    $("div").hide();
}
$('button').on("click", function(e) {        
    if($("#div").css("display") == "none") {          
        $("#div").show();        
    } else {          
        $("#div").hide();        
    }        
    e = e || event;
    stopFunc(e);      
});
      
$('#div').on("click", function(e) {        
    e = e || event;
    stopFunc(e);      
});    
function stopFunc(e) {      
    e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;    
}

点击button出现div菜单,再次点击button隐藏菜单或点击div之外页面其余地方隐藏div菜单。ide

相关文章
相关标签/搜索