单击正文时关闭模态

时间:2022-02-01 11:07:50

I have made a simple pure modal with CSS and Javascript. Here's the code:
HTML:

我用CSS和Javascript制作了一个简单的纯模态。这是代码: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? Or is there another solution?

你可以在这个小提琴上看看。问题是,如果我在模态本身内部单击,它会关闭,我想与模态进行交互。我需要CSS屏蔽吗?还是有其他解决方案吗?

3 个解决方案

#1


1  

Use StopPropagation, try this:

使用StopPropagation,试试这个:

$(".modal").click(function(e) {
        e.stopPropagation();
});

Check the Demo Fiddle

检查演示小提琴

#2


1  

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);
    }
});

#3


0  

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/

#1


1  

Use StopPropagation, try this:

使用StopPropagation,试试这个:

$(".modal").click(function(e) {
        e.stopPropagation();
});

Check the Demo Fiddle

检查演示小提琴

#2


1  

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);
    }
});

#3


0  

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/