javascript - keep modal open despite clicking on it
问题描述
I'm trying to get a toggling modal to stay open even when it's clicked on. It has multiple elements inside of it as well, and if one of those is clicked it still needs to stay open. I asked a similar question about click events and event.target: close modal on click on body and this is a build off of that.
I figured out the previous question, which leaves me with this:
$(function(e) {
$("#filter-button").click(function(e) {
$(".dialog").toggleClass("show");
});
$(window).click(function(e) {
if((e.target.tagName.toLowerCase() != 'button') && ($(".dialog").hasClass("show"))) {
$(".dialog").removeClass("show");
} else if (e.target.className.toLowerCase() == 'dialog') {
return false;
}
});
});
.dialog {
display: none;
width: 300px;
height: 300px;
background-color: red;
}
.show {
display: block !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="filter-button">SHOW/HIDE</button>
<div class="dialog">
<h1>Hi</h1>
<ul>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ul>
</div>
To explain what I'm trying to do - if the event target in the first if in the window click event is not the button and the dialog is showing, then remove it (expected functionality) - I now need to keep it open if it's clicked inside.
My attempt is this piece:
...
else if (e.target.className.toLowerCase() == 'dialog') {
return false;
}
...
What I thought was going to happen is that if the div is clicked, it will return: false;
and stay open, preventing the dialog from closing. But it closes anyway. I also need to somehow target all the elements inside of it.
I'm not sure at this point how to move forward? Do I need to include all elements inside the dialog somehow?
解决方案
You need to stop the event from bubbling up to the parent element (which will close the modal, as expected). You can do that with the following code:
$('.dialog').click(function(event) {
event.stopPropagation();
});
推荐阅读
- arduino - Arduino shield SIM900 不响应 AT 命令
- python - 如何根据 Python 中的条件创建结果组合矩阵?
- kotlin - Kotlin - 在 hashmap 上使用 apply 或 also 不能按预期工作
- facebook - 主域和子域不同的 Facebook 评论系统
- node.js - 护照认证超时
- javascript - 重新排序和过滤对象数组
- android - Ionic Android 支持的最低 Gradle 版本为 4.6。当前版本是 4.1
- scom - SCOM - 查看上次登录的用户
- vba - Excel VBA - 密码保护工作表
- javascript - 链接可观察对象 Angular 5 / Rxjs