切换后无法单击按钮

时间:2018-10-12 09:04:57

标签: javascript jquery html css

我无法使用按钮关闭下拉菜单,但是当我单击外部页面时可以关闭它。

Working Demo here

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();
  }
 });

请帮助我。

3 个答案:

答案 0 :(得分:2)

$(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();不会阻止同一元素上的其他处理程序运行。

答案 1 :(得分:2)

只需U鼠标单击即可执行一项操作。您的JS必须是:

var $menu = $('.menu');
var $toggle = $('.toggle');

$(document).mouseup(function (e) {
  if ($toggle.is(e.target)) {
    $menu.toggle()
  } else {
    $menu.hide();
  }
});

答案 2 :(得分:1)

如果要打开和关闭按钮。只需删除第二个函数,您的代码即可使用。

var $menu = $('.menu');

$('.toggle').click(function () {
  $menu.toggle();
});