Javascript 如何在外部单击时关闭模态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37573608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make modal close on click outside
提问by Hyman H
I have used this JavaScript below:
我在下面使用了这个 JavaScript:
$('body').click(function() {
if (!$(this.target).is('#popUpForm')) {
$(".modalDialog").hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="openModal" class="modalDialog">
<div class="modalClose">
<a href="#close" title="Close" class="close-circle" style="color:white; text-decoration:none; font-size:14px;"></a>
<div id="signup-header">
<h4>Request a brochure, with a free demo</h4>
<h5>Please Fill in the form below: </h5>
</div>
<form id="popUpForm" class="tryMeForm" name="" onsubmit="return formCheck(this);" method="post" action="">
<div class="InputGroup">
<input type="text" name="name" id="name" value="" placeholder="First Name*" />
</div>
<div class="InputGroup">
<input type="text" name="lastname" id="lastname" value="" placeholder="Last Name*" />
</div>
<div class="InputGroup">
<input type="text" name="Email" id="Email" value="" placeholder="Email Address*" />
</div>
<div class="InputGroup">
<input type="text" name="Phone" id="Phone" value="" placeholder="Phone Number*" />
</div>
<div class="InputGroup">
<textarea name="message" id="message" class="" placeholder="How we can help?"></textarea>
</div>
<div class="submit">
<input class="button_submit1 button-primary button1" type="submit" value="Submit" />
</div>
</form>
</div>
</div>
</body>
This allows me to close the modal when clicking outside of it. However, it closes even when I click inside as well. How can I make it close only on outside and the close button, but not inside, so the users can still enter their details?
这允许我在单击它的外部时关闭它。但是,即使我也单击内部,它也会关闭。我怎样才能让它只在外面和关闭按钮上关闭,而不是在里面,这样用户仍然可以输入他们的详细信息?
采纳答案by Hyman H
This seemed to be the code that worked out for me in the end:
这似乎是最终对我有用的代码:
$(document).click(function (e) {
if ($(e.target).is('#openModal')) {
$('#openModal').fadeOut(500);
}
});
$("#modalNo").click(function () {
$("#openModal").fadeOut(500);
});
$(".close").click(function () {
$("#openModal").fadeOut(500);
});
$(".close-circle").click(function () {
$("#openModal").fadeOut(500);
});
回答by Zakaria Acharki
Use the parent node #openModal
(container) instead of #popUpForm
(form) :
使用父节点#openModal
(容器)而不是#popUpForm
(形式):
$('body').click(function (event)
{
if(!$(event.target).closest('#openModal').length && !$(event.target).is('#openModal')) {
$(".modalDialog").hide();
}
});
回答by nbalaguer
Adding to this for future readers.
为将来的读者添加此内容。
Another way to dismiss the modal when clicking outside involved taking advantage of the bubbling nature of the javascript events.
在外部单击时关闭模态的另一种方法是利用 javascript 事件的冒泡特性。
In a typical modal HTML structure
在典型的模态 HTML 结构中
<body>
<div id="root">
-- Site content here
</div>
<div id="modal-root">
<div class="modal"></div>
</div>
</body>
clicking on .modal
will cause the click event to propagate like this .modal -> #modal-root -> body
while clicking outside the modal will only go through #modal-root -> body
.
单击.modal
将导致单击事件像这样传播,.modal -> #modal-root -> body
而在模态外单击只会通过#modal-root -> body
.
Since we can stop the propagation of click events completely, and if that does not interfere with any other code, we only need to listen for click events in both .modal
and #modal-root
. A "modal-root" click will dismiss the modal, and a "modal" click will stop propagating the click event so never reaches the "modal-root".
由于我们可以完全停止点击事件的传播,并且如果这不会干扰任何其他代码,我们只需要在.modal
和 中监听点击事件#modal-root
。“模态根”点击将关闭模态,“模态”点击将停止传播点击事件,因此永远不会到达“模态根”。
For extra clarity, here's the code working in codepen.io: https://codepen.io/nbalaguer/pen/PVbEjm
为了更加清晰,这里是 codepen.io 中的代码:https://codepen.io/nbalaguer/pen/PVbEjm
回答by Marcela Nakakomi
This is working for me: I have an image inside of the modal window, so if someone click outside the image (centered):
这对我有用:我在模态窗口中有一个图像,所以如果有人点击图像外(居中):
html code:
html代码:
<div id="modal_div"><img id="image_in_modal_div" src="image.jpg" /></div>
ccs code:
cc代码:
#modal_div {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: transparent;
}
#image_in_modal_div {
left: 50%;
top: 30%;
position: absolute;
}
mixed jquery and javascript code:
混合 jquery 和 javascript 代码:
$( document ).ready(function() {
$("#element_that_opens_modal").click(function(){
$("#modal_div").show();
});
window.onclick = function(event) {
if (event.target.id != "image_in_modal_div") {
$("#modal_div").hide();
}
}
});
回答by Ryan
This is not the most efficient way, but it will work. The idea is to traverse the tree and check if the parent is the id of the one where you don't want to hide on click anywhere except it.
这不是最有效的方法,但它会奏效。这个想法是遍历树并检查父级是否是您不想在除它之外的任何地方单击时隐藏的那个的 ID。
$(document).on('click', function(e) {
var p = e.target;
while(p) {
console.log(p);
if(p.id) {
if(p.id == 'openModal') {
return;
}
}
p = p.parentElement;
}
$("#openModal").hide();
});
回答by Abdullah Ayd?n
$('body').on('click', '.modal-open', function(e) {
$('.modal-background, .modal').show();
e.preventDefault();
})
.on('click', '.modal-close', function(e) {
$('.modal-background, .modal').hide();
e.preventDefault();
});
if ( !$('.modal-background.modal-close').length ) {
$('<div/>').addClass('modal-background modal-close').appendTo('body');
}
body {
background: #ccc;
overflow-y: scroll;
padding: 15px;
}
button {
cursor: pointer;
}
.modal {
width: 400px;
margin: 5% auto 0 -200px;
padding: 10px;
background: #eee;
display: none;
position: absolute;
left: 50%;
top: 0;
z-index: 10;
}
.modal-background {
background: rgba(0, 0, 0, 0.5);
/* background: transparent; */
/* position: absolute; */
position: fixed;
z-index: 9; /* .modal[zIndex] - 1 */
bottom: 0;
right: 0;
left: 0;
top: 0;
display: none;
}
<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>
<button type="button" class="modal-open">Open modal</button>
<div class="modal">
<p>
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
</p>
<p>
<button type="button" onclick="$('.dummy-container').toggle()">Toggle something for testing</button>
<p>
<p class="dummy-container" style="display: none;">
Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
</p>
<p>
<button type="button" class="modal-close">Close modal</button>
</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>