我无法使用按钮关闭下拉列表,但我可以在单击外部页面时将其关闭。
var $menu = $('.menu');
$('.toggle').click(function () {
$menu.toggle();
});
$(document).mouseup(function (e) {
if (!$menu.is(e.target) // if the target of the click isn't the container...
&& $menu.has(e.target).length === 0) // ... nor a descendant of the container
{
$menu.hide();
}
});
请大家帮帮我。
最佳答案
$(document).ready(function(){
var $menu = $('.menu');
$('.toggle').click(function (e) {
e.stopPropagation();
$menu.toggle();
});
$('.container').click(function (e) {
e.stopPropagation();
$menu.toggle();
});
});
.dropdown {
margin: 200px auto;
position: relative;
width: 50%;
}
.toggle, .dropdown-menu {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.bundle.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row">
<div class="text-center col-xs-12">
<h1>jQuery: click outside to close menu</h1>
<p>Click the button to toggle the dropodown menu.</p>
<p>Then click outside dropdown menu to close.</p>
<div class="dropdown">
<a href="#" title="" class="btn btn-default toggle">Toggle menu</a>
<ul class="dropdown-menu menu">
<li class="dropdown-item">List item 1</li>
<li class="dropdown-item">List item 2</li>
<li class="dropdown-item">List item 3</li>
</div>
</div>
</div>
</div>
使用 event.stopPropagation();
这不会阻止同一元素上的其他处理程序运行。
关于javascript - 切换后无法单击按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52776011/