从可点击的行为中豁免形式

时间:2015-02-20 18:13:40

标签: javascript jquery html css

目前我有一些文本框包含在一个展开的顶部栏中,即网页顶部的一个条带,当点击它时,切换以下展开/关闭行为。

var toggle = true;
$("#expandable").click(function() {
    if (toggle == true){
        $(this).stop().animate({"height":"300px"},500);
        toggle = false;
    } else {
        $(this).stop().animate({"height":"50px"},500);
        toggle = true;
    }
});

现在,我唯一的问题是,当我点击文本框时,展开的div认为它被点击了(足够公平)。但是当我点击表格时,我不希望顶栏关闭。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:3)

如果在输入元素上发生事件,则阻止事件冒泡:

$("#expandable :input").click(function(e) {
    e.stopPropagation();
});

这种点击事件不会到达#expandable元素上的点击处理程序。

特殊选择器:input匹配输入,textareas,选择框。

答案 1 :(得分:0)

var toggle = true;
$("#expandable").off('click');
$("#expandable").on('click',function() {
    if (toggle == true){
        $(this).stop().animate({"height":"300px"},500);
        toggle = false;
    } else {
        $(this).stop().animate({"height":"50px"},500);
        toggle = true;
    }
});

您也可以这样写它以防止冒泡。