jQuery 单击关闭时保持 Bootstrap 下拉菜单打开

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19740121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:31:59  来源:igfitidea点击:

Keep Bootstrap Dropdown Open When Clicked Off

javascriptjquerytwitter-bootstraptwitter-bootstrap-3drop-down-menu

提问by kleban

If the dropdown is visible, and I click outside the dropdown it closes. I need it to not close.

如果下拉菜单可见,我在下拉菜单外单击它会关闭。我需要它不关闭。

From the documentation:

从文档:

When opened, the plugin also adds .dropdown-backdropas a click area for closing dropdown menus when clicking outside the menu.

打开时,插件还会添加.dropdown-backdrop作为单击区域,用于在菜单外单击时关闭下拉菜单。

What JavaScript can I add to prevent the drop down from closing?

我可以添加什么 JavaScript 来防止下拉菜单关闭?

回答by KyleMit

From the events section of the Bootstrapdropdowndocumentation:

Bootstrapdropdown文档的事件部分:

hide.bs.dropdown: This event is fired immediately when the hide instance method has been called.

hide.bs.dropdown: 调用隐藏实例方法时立即触发此事件。

For starters, to prevent the dropdown from closing, we can just listen to this event and stop it from proceeding by returning false:

对于初学者来说,为了防止下拉菜单关闭,我们可以只监听这个事件并通过返回来阻止它继续false

$('#myDropdown').on('hide.bs.dropdown', function () {
    return false;
});


For a complete solution, you probably want to allow it to close when the dropdown itself is clicked. So only some of the timewe'll want to prevent the box from closing.

对于完整的解决方案,您可能希望在单击下拉菜单本身时允许它关闭。所以只有在某些时候我们会想要阻止盒子关闭。

To do this we'll set .data()flags in two more events raised by the dropdown:

为此,我们将.data()在下拉列表引发的另外两个事件中设置标志:

  • shown.bs.dropdown- When shown, we'll set .data('closable')to false
  • click- When clicked, we'll set .data('closable')to true
  • shown.bs.dropdown- 显示时,我们将设置.data('closable')false
  • click- 点击后,我们将设置.data('closable')true

Thus, if the hide.bs.dropdownevent was raised by a clickon the dropdown, we'll allow a close.

因此,如果hide.bs.dropdown事件是由click下拉列表中的 a 引发的,我们将允许关闭。

Live Demo in jsFiddle

jsFiddle 中的现场演示

JavaScript

JavaScript

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

HTML(note I've added the class keep-opento the dropdown)

HTML (注意我已将类添加keep-open到下拉列表中)

<div class="dropdown keep-open">
    <!-- Dropdown Button -->
    <button id="dLabel" role="button" href="#" class="btn btn-primary"
            data-toggle="dropdown" data-target="#" >
        Dropdown <span class="caret"></span>
    </button>

    <!-- Dropdown Menu -->
    <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
        <li><a href="#">Action</a></li>
        <li><a href="#">Another action</a></li>
        <li><a href="#">Something else here</a></li>
        <li class="divider"></li>
        <li><a href="#">Separated link</a></li>
    </ul>
</div>

回答by Mike Kane

Version changes in some dependency have caused KyleMit's, and most other solutions to no longer work. I dug into a bit further and for some reason a click()is sent when Bootstrap tries and fails hide.bs.dropdown, followed by another call to hide.bs.dropdown. I got around this issue by forcing the closing click()to occur on the button itself, not the entire dropdown menu.

某些依赖项中的版本更改导致 KyleMit 和大多数其他解决方案不再有效。我深入研究了一下,出于某种原因,click()当 Bootstrap 尝试并失败时会发送a hide.bs.dropdown,然后是另一个调用hide.bs.dropdown. 我通过强制关闭click()发生在按钮本身而不是整个下拉菜单上来解决这个问题。

Live Demo in Bootply

Bootply 中的现场演示

JavaScript

JavaScript

$('.keep-open').on({
    "shown.bs.dropdown": function() { $(this).attr('closable', false); },
    //"click":             function() { }, // For some reason a click() is sent when Bootstrap tries and fails hide.bs.dropdown
    "hide.bs.dropdown":  function() { return $(this).attr('closable') == 'true'; }
});

$('.keep-open').children().first().on({
  "click": function() {
    $(this).parent().attr('closable', true );
  }
})

HTML

HTML

<h2>Click the dropdown button </h2>
<p>It will stay open unless clicked again to close </p>

<div class="dropdown keep-open">
    <!-- Dropdown Button -->
    <button id="dLabel" role="button" href="#" data-toggle="dropdown" data-target="#" class="btn btn-primary">
        Dropdown <span class="caret"></span>
    </button>

    <!-- Dropdown Menu -->
    <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
        <li><a href="#">Action</a></li>
        <li><a href="#">Another action</a></li>
        <li><a href="#">Something else here</a></li>
        <li class="divider"></li>
        <li><a href="#">Separated link</a></li>
    </ul>
</div>

回答by bhavik

$('.dropdown.keep-open').on({
    "shown.bs.dropdown": function() { this.closable = true; },
    "click":             function(e) { 
        var target = $(e.target);
        if(target.hasClass("btn-primary")) 
            this.closable = true;
        else 
           this.closable = false; 
    },
    "hide.bs.dropdown":  function() { return this.closable; }
});
body {
    margin: 10px;
}
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<h2>Click the dropdown button </h2>
<p>It will stay open unless clicked again to close </p>

<div class="dropdown keep-open">
    <!-- Dropdown Button -->
    <button id="dLabel" role="button" href="#"
       data-toggle="dropdown" data-target="#" 
       class="btn btn-primary">
        Dropdown <span class="caret"></span>
    </button>
    
    <!-- Dropdown Menu -->
    <ul class="dropdown-menu" role="menu" 
        aria-labelledby="dLabel">
        <li><a href="#">Action</a></li>
        <li><a href="#">Another action</a></li>
        <li><a href="#">Something else here</a></li>
        <li class="divider"></li>
        <li><a href="#">Separated link</a></li>
    </ul>
</div>




<!-- Post Info -->
<div style='position:fixed;bottom:0;left:0;    
            background:lightgray;width:100%;'>
    About this SO Question: <a href='http://stackoverflow.com/q/19740121/1366033'>Keep dropdown menu open</a><br/>
    Fork This Skeleton Here <a href='http://jsfiddle.net/KyleMit/kcpma/'>Bootrsap 3.0 Skeleton</a><br/>
    Bootstrap Documentation: <a href='http://getbootstrap.com/javascript/#dropdowns'>Dropdowns</a><br/>
<div>

回答by andrew dibiasio

I found a solution that requires no new js. Don't use a drop down and use bootstrap collapse instead. I still use some dropdown classes to style it like a dropdown.

我找到了一个不需要新js的解决方案。不要使用下拉菜单,而是使用 bootstrap 折叠。我仍然使用一些下拉类将其设置为下拉样式。

<div class="dropdown">
    <button class="dropdown-toggle" type="button" data-toggle="collapse" data-target="#myList">Drop Down
    <span class="caret"></span></button>
    <div id="myList" class="dropdown-menu">
        <input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
        <input type="checkbox" name="vehicle" value="Car"> I have a car<br></div>

回答by Honga

I managed to use a combination of KyleMitt's solution above and ran into issues when using this within a Footable object (I believe this is due to the dynamic creation of the table). I applied .keep-open to the .dropdown .div at the top level.

我设法结合使用上面的 KyleMitt 解决方案,并在 Footable 对象中使用它时遇到了问题(我相信这是由于表格的动态创建)。我将 .keep-open 应用于顶层的 .dropdown .div 。

$('#contact_table').on("click", '.keep-open', function () {
    this.closable = false;
});

$('#contact_table').on("shown.bs.dropdown", '.keep-open', function () {
    this.closable = true;
});
$('#contact_table').on("hide.bs.dropdown", '.keep-open', function () {
    let ret = this.closable;
    this.closable = true;
    return ret;
});

The functionality of this code allows you to click outside to close the dropdown, but clicking on items within it would maintain it being open. Please let me know if you have any suggestions/comments on this and I will attempt to edit.

此代码的功能允许您单击外部以关闭下拉列表,但单击其中的项目将使其保持打开状态。如果您对此有任何建议/意见,请告诉我,我会尝试进行编辑。

回答by Carl Champagne

Mike Kane's solution worked most of the time, but there was a case where the hide.bs.dropdownevent was firing before the click()event which caused the dropdown to not close when it should have.

Mike Kane 的解决方案大部分时间都有效,但有一种情况是hide.bs.dropdown事件在click()事件发生之前触发,导致下拉菜单在它应该关闭的时候没有关闭。

I have come up with with another method that checks the clickEventobject in the event. My original plan was to go up the DOM and check that the clickEventtarget was or was not a child of the dropdown, but found that if you click inside the dropdown clickEventis undefined, and if you click outside of it the event is an object.

我想出了另一种方法来检查clickEvent事件中的对象。我最初的计划是访问 DOM 并检查clickEvent目标是否是下拉列表的子项,但发现如果您在下拉列表内单击clickEvent是未定义的,如果您在下拉列表外单击,则事件是一个对象。

So it's just a simple check on whether the clickEventexists as an object.

所以这只是一个简单的检查是否clickEvent作为对象存在。

$('.dropdown.keep-open').on({
    "hide.bs.dropdown":  function(e) {
        return (typeof(e.clickEvent) != 'object');
    }
});

回答by Wissarut Nachom

$('.dropdown.keep-open').on({
    "shown.bs.dropdown": function(){ 
        this.closable = true; 
    },
    "hide.bs.dropdown": function(e){ 
        if(!this.closable){
            this.closable = true;
            return false;
        }
        return this.closable; 
    },
    "click": function(e){ 
        this.closable = false;
    }
});

回答by Tomasz Majerski

Other solution for this. Keep dropdown open after clicking inside .dropdown-menu:

其他解决方案。单击内部 .dropdown-menu 后保持下拉菜单打开:

$('.heading .options .dropdown').on({
    "shown.bs.dropdown":function(){this.closable = true;},
    "click":            function(e){
        var target = $(e.target);
        var d = target.data();
        if(typeof d.toggle != 'undefined' && d.toggle == 'dropdown')
            this.closable = true;
        else {
            var p = target.parent();
            var dd = p.data();
            if(typeof dd.toggle != 'undefined' && dd.toggle == 'dropdown')
                this.closable = true;
            else {
                if(target.hasClass('dropdown-menu'))
                    this.closable = false;
                else {
                    var pp = target.parent('.dropdown-menu');
                    if(typeof pp != 'undefined')
                        this.closable = false;
                    else
                        this.closable = true;
                }
            }
        }
    },
    "hide.bs.dropdown": function(){return this.closable;}
});

回答by Arron Mabrey

Keep dropdown open after clicking inside .dropdown-menu

单击内部 .dropdown-menu 后保持下拉菜单打开

  $(document.body).on({
    "shown.bs.dropdown": function(){ this.closable = true; },
    "hide.bs.dropdown": function(){ return this.closable; },
    "click": function(e){ this.closable = !$(e.target).closest(".dropdown-menu").length; },
  },".dropdown.keepopen");