当我单击该按钮时,该按钮切换一个特定的类并打开一些东西,这是可行的,但当我试图键入一段代码,当我单击外部对象时,该代码将关闭该对象,它将无法工作。
$(function() {
  $('button').on('click', function() {
    $('.list').toggle();
    $('button').toggleClass('something');
  });
  $(document).on('click', function(e) {
    if (e.target !== 'list, button') {
      $('.list').hide();
    }
  });
});.list {
  width: 100px;
  height: 150px;
  background: lightgray;
  display: none;
}
button {
  background: green
}
.something {
  background: red;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='list'></div>
<button>button</button>
发布于 2017-10-02 00:03:43
尝试下面的代码,在这里您将打开列表并移动到它上面,但是当您单击按钮和列表的外部时,列表将被隐藏:
var change ="y";
$('button').on('click', function() {
   if(change == "y") { $(".list").show(); }});
$('button').on('blur', function() {
    if(change == "x") { $(".list").hide();
    change="y";}});
  
      
$('.list').on('mouseover', function() { change="y";});
$('.list').on('mouseout', function() {change="x";
$('button').focus();});.list {
  width: 100px;
  height: 150px;
  background: lightgray;
  display: none;
}
button {
  background: green
}
.something {
  background: red;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class='list'></div>
<button>button</button>
发布于 2017-10-01 23:32:11
这是因为您有一个display: none的CSS声明。您还可能希望向.list添加一些内容(因此可以隐藏),如下例所示:
$(function() {
  $(document).on('click', function(e) {
    if (e.target !== 'list, button') {
      $('.list').hide();
    }
  });
});.list {
  width: 100px;
  height: 150px;
  background: lightgray;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='list'>List</div>
希望这会有帮助!)
https://stackoverflow.com/questions/46517848
复制相似问题