JQuery:点击div之外的任何地方的执行功能

时间:2014-02-27 00:56:05

标签: jquery

    function handler1(){
        $("#navi_touch").css("visibility","visible");
        $("#navitouchbutton").css("background","red");
        $("#navitouchbutton").one("click",handler2);
        }
    function handler2(){
        $("#navi_touch").css("visibility","hidden");
        $("#navitouchbutton").css("background","#000");
        $("#navitouchbutton").one("click",handler1);
        }
    $("#navitouchbutton").one("click", handler1);

现在折叠菜单的唯一方法是单击#navitouchbutton。当用户点击#navi_touch以外的任何地方时,如何折叠此菜单(隐藏#navi_touch)?

2 个答案:

答案 0 :(得分:0)

将处理程序注册到文档对象

function handler1() {
    $("#navi_touch").css("visibility", "visible");
    $("#navitouchbutton").css("background", "red");
    $(document).one("click", handler2);
}

function handler2() {
    $("#navi_touch").css("visibility", "hidden");
    $("#navitouchbutton").css("background", "#000");
    $("#navitouchbutton").one("click", handler1);
}
$("#navitouchbutton").one("click", handler1);

答案 1 :(得分:0)

可以做到这一点的一种方法是在文档上绑定click事件,然后检查您单击的元素是否是#nav_touch的子元素。

样本处理程序:

$(document).on('click', function(e){
    if( $(e.target).parents('#navi_touch').length ) return;

    $("#navi_touch").css("visibility", "hidden");
    $("#navitouchbutton").css("background", "#000");
});