我有一个简单的显示面板,它使用toggleClass和切换类“ active”来显示面板。面板显示后,我还希望“取消锁定”并删除“活动”类的选项,以通过单击身体上的任意位置来隐藏面板。
这是我的jQuery
$(".number-people .trigger").click(function(){
$(".number-people-popup").toggleClass("active");
});
我尝试做
$("body").click(function(){
$(".number-people-popup").removeClass("active");
});
但是它总是会发生冲突。我敢肯定有一种简单的方法。
这是一个jsFiddle:https://jsfiddle.net/alexgomy/8r0Lkj2b/4/
谢谢
答案 0 :(得分:1)
您正在寻找stopPropagation()来阻止事件冒泡
修改
<select>
中包含div
,以反映对评论的疑问
$(".number-people .trigger").click(function(e) {
$(".number-people-popup").toggleClass("active");
e.stopPropagation();
});
$("body").click(function(e) {
if (!$(e.target).hasClass("number-people-popup") && $(e.target).parents(".number-people-popup").length === 0) {
$(".number-people-popup").removeClass("active");
}
});
.trigger {
cursor: pointer;
}
.number-people-popup {
display: none;
border: 1px solid #000;
padding: 30px;
width: 150px;
text-align: center;
}
.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="number-people">
<p class="trigger">
Click to trigger
</p>
</div>
<div class="number-people-popup">
Reveal panel here
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</div>
<br><br><br><br><br> Once triggered i want to close by clicking anywhere in the background.
答案 1 :(得分:1)
很快:
$('html').click(function() {
$(".number-people-popup").removeClass("active")
});
$(".number-people .trigger").on('click', function(e){
e.stopPropagation();
$(".number-people-popup").toggleClass("active");
});
.trigger{cursor:pointer;}
.number-people-popup{display:none;border:1px solid #000;padding:30px;width:150px;text-align:center;}
.active{display:block;}
<div class="number-people">
<p class="trigger">
Click to trigger
</p>
</div>
<div class="number-people-popup">
Reveal panel here
</div>
<br><br><br><br><br>
Once triggered i want to close by clicking anywhere in the background.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>