延迟关闭bootstrap下拉列表

时间:2015-06-08 02:26:08

标签: javascript jquery twitter-bootstrap

我正在尝试修改bootstrap下拉列表的行为。首先,我想阻止在您单击页面上的其他位置时关闭下拉列表。我用这段代码做到了:

$('#filters').on({
    "shown.bs.dropdown": function() { this.closable = false; },
    "click":             function() { this.closable = true; },
    "hide.bs.dropdown":  function() { return this.closable; }
});

现在,当您单击其中的链接时,我想延迟关闭下拉列表。我想这样做,因为在您实际离开页面并加载新页面之前单击链接时,下拉列表会立即关闭。

以下是我目前所拥有的a fiddle

2 个答案:

答案 0 :(得分:2)

DEMO

怎么样?

我想建议你两件事:

  
      
  • eventlisteners上添加.btn-group,而不是#filters   很容易检查点击了哪个dropdown
  •   
  • 将所需动画添加到click事件
  •   

所以根据上面的建议代码如下:

$('.btn-group').on({
    "shown.bs.dropdown": function () {
        this.closable = false;
    },
    "click": function () {
        this.closable = true;
            if(!$(this).hasClass('open'))
                $(this).find('.dropdown-menu').stop(true, true).slideToggle();
            else
                $(this).find('.dropdown-menu').stop(true, true).delay(600).slideToggle();

    },
    "hide.bs.dropdown": function () {
        return this.closable;
    }
});

更新:

根据您的评论,我希望这是您希望实现的目标:

<强> DEMO

$('.btn-group').on({
    "shown.bs.dropdown": function () {
        this.closable = false;
    },
        "click": function () {
            this.closable = true;
            $('.btn-group').not($(this)).find('.dropdown-menu').stop(true, true).slideUp();//Close all the dropdowns except this
            if(!$(this).hasClass('open'))
            {
                $(this).find('.dropdown-menu').stop(true, true).slideToggle();//open only this dropdown
                $('.btn-group').not($(this)).removeClass('open'); //remove the focus effect from other dropdowns
            }
            else
                $(this).find('.dropdown-menu').stop(true, true).delay(600).slideToggle();

    },
        "hide.bs.dropdown": function () {
        return this.closable;
    }
});

答案 1 :(得分:0)

好吧,我认为你必须稍微破解正常的bootstrap下拉事件序列,但是只有当this.closable为true时,才可以使用带有if / else的事件来触发delay + slideUp()。然后,由于你无法在hide.bs.dropdown事件中“返回true”,你必须删除'open'类,然后在下次单击下拉列表时自己触发'show()'。像这样:

这里有一个工作下拉菜单 - 你必须为每个下拉列表制作唯一的ID,如果你有倍数,然后可能使用event.target。[something]来识别正确的下拉菜单切换...... / p>

http://jsfiddle.net/yp44tt9e/2/

$('#filters').on({
    "show.bs.dropdown": function() {
        console.log($(this));
        $(this).find('.dropdown-menu').show();
    },
    "shown.bs.dropdown": function () {
        this.closable = false;
    },
        "click": function () {
        this.closable = true;
    },
        "hide.bs.dropdown": function (e){
            if(this.closable){
                e.preventDefault();
                $(this).find('.dropdown-menu')
                    .first()
                    .stop(true, true)
                    .delay(600)
                    .slideUp('slow', function(){
                        $('.btn-group').removeClass('open');
                    });
             }else{
                return this.closable;
             }
    }
});