单击按钮显示div,然后单击其外部时隐藏此div

时间:2016-01-22 13:06:51

标签: javascript jquery

HTML

<div id="selectPeriodRangePanel">
    <p>Test</p>
</div>

<button id="period_select_range_btn">Select Range</button>

JQUERY

$("#period_select_range_btn").off().on("click", function(){
    $("#selectPeriodRangePanel").toggle();
});

当我点击按钮时,会打开 selectPeriodRangePanel DIV。当我点击它之外时,我想隐藏这个DIV

我该怎么做?

3 个答案:

答案 0 :(得分:12)

试试这个

$(document).on("click", function(e){
    if($(e.target).is("#period_select_range_btn")){
      $("#selectPeriodRangePanel").show();
    }else{
        $("#selectPeriodRangePanel").hide();
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selectPeriodRangePanel" style="display:none">
    <p>Test</p>
</div>

<button id="period_select_range_btn">Select Range</button>

答案 1 :(得分:5)

您可以为文档元素设置单击处理程序,如果单击发生在外部,则可以隐藏它。

&#13;
&#13;
$("#period_select_range_btn").off().on("click", function() {
  $("#selectPeriodRangePanel").toggle();
});
$(document).click(function(e) {
  if ($(e.target).closest('#selectPeriodRangePanel, #period_select_range_btn').length == 0) {
    $("#selectPeriodRangePanel").hide();
  }
})
&#13;
body {
  min-height: 500px;
  background-color: lightblue;
}
#selectPeriodRangePanel {
  background-color: lightgrey;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selectPeriodRangePanel">
  <p>Test</p>
</div>

<button id="period_select_range_btn">Select Range</button>
&#13;
&#13;
&#13;

答案 2 :(得分:3)

我会这样做:

试试这个

&#13;
&#13;
$(document).on("click", function(e) {
  var el = $(e.target).closest("#selectPeriodRangePanel, #period_select_range_btn").length != 0;
  $("#selectPeriodRangePanel").toggle(el);

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selectPeriodRangePanel" style="display:none">
  <p>Test</p>
</div>

<button id="period_select_range_btn">Select Range</button>
&#13;
&#13;
&#13;