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
。
我该怎么做?
答案 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)
您可以为文档元素设置单击处理程序,如果单击发生在外部,则可以隐藏它。
$("#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;
答案 2 :(得分:3)
我会这样做:
试试这个
$(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;