我知道很难为我的问题提供代码,但是我想知道如何使Bootstrap下拉菜单在默认情况下打开后无法关闭(保持打开状态)?
谢谢
答案 0 :(得分:0)
您必须使用2个功能,其中一个onclick
dropdown
和一个onclick
body
使用e.stopPropagation();
来防止关闭...
var flag=true;
$( ".dropdown-toggle" ).click(function(e) {
if (!flag)
e.stopPropagation();
else
flag=false;
});
$(document).on('click', ':not(.dropdown)', function(e) {
if ($(this).closest('.dropdown').length == 0) {
e.stopPropagation();
}
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="#">HTML</a></li>
<li><a href="#">CSS</a></li>
<li><a href="#">JavaScript</a></li>
</ul>
</div>
</div>
答案 1 :(得分:0)
此解决方案在Bootstrap隐藏(hide.bs.dropdown)事件上停止传播,从而阻止其继续进行到隐藏(hidden.bs.dropdown)事件。您可以在这里阅读更多内容:http://css-tricks.com/dangers-stopping-event-propagation/
我个人更喜欢这种方式,因为它使用内置的Bootstrap下拉事件,可以在以下位置找到该事件:http://getbootstrap.com/javascript/#dropdowns-events
$(function () {
$('.dropdown.keep-open').on({
"shown.bs.dropdown": function () {
$(this).data('closable', false);
},
"click": function (event) {
$(this).data('closable', false);
},
"hide.bs.dropdown": function (event) {
temp = $(this).data('closable');
$(this).data('closable', true);
return temp;
}
});
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<h3>Default behaviour</h3>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
<hr/>
<h3>Preventing bootstrap dropdown from closing on click</h3>
<div class="dropdown keep-open">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>