[英]Close a modal when the body is clicked
I have made a simple pure modal with CSS and Javascript. 我使用CSS和Javascript制作了一个简单的纯模式。 Here's the code:
这是代码:
HTML: HTML:
<button data-role="toggle-modal" data-toggle="#demo">Trigger</button>
<div class="modal-wrapper" id="demo" style="display: none">
<div class="modal">
Modal content
</div>
</div>
CSS: CSS:
.modal {
margin: 10% auto;
padding: 1em;
overflow: hidden;
width: 40%;
box-sizing: border-box;
border: 1px solid rgba(0, 0, 0, .5);
background: white;
text-align: center;
}
.modal-wrapper {
z-index: 1000;
position: fixed;
overflow: hidden;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, .4);
}
JS: JS:
$('button[data-role="toggle-modal"]').click(function() {
var target = ($(this).attr('data-toggle'));
$(target).fadeIn(175);
});
$('.modal-wrapper').click(function() {
$(this).fadeOut(175);
});
You can check it out on this fiddle . 您可以在这个小提琴上查看一下。
The problem is, if I click inside the modal itself, it closes, and I want to interact with the modal. 问题是,如果我在模态本身内部单击,它将关闭,并且我想与模态进行交互。 Do I need CSS masking here?
我需要CSS遮罩吗? Or is there another solution?
还是有其他解决方案?
You need to prevent the click event is triggered in the child element. 您需要防止在子元素中触发click事件。
$('.modal-wrapper').click(function(e) {
if(e.target == e.currentTarget) {
$(this).fadeOut(175);
}
});
Use StopPropagation , try this: 使用StopPropagation ,尝试以下操作:
$(".modal").click(function(e) {
e.stopPropagation();
});
Check the Demo Fiddle 检查演示小提琴
Just check for e.target
in your code and based on that, fade the dialog. 只需检查代码中的
e.target
,然后基于该目标淡出对话框即可。
Example: 例:
$('.modal-wrapper').click(function(e) {
if($(e.target).is('.modal-wrapper')) $(this).fadeOut(175);
});
Demo: http://jsfiddle.net/gprf6Lna/3/ 演示: http : //jsfiddle.net/gprf6Lna/3/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.