简体   繁体   中英

Fading out Javascript “modal window” when background is clicked?

I have a modal-like window in CSS that I fade in with Javascript. The HTML is like this:

<div class="whiteout">
<div class="modal">
    <a class="modal-close" title="Close"></a>
    // modal window content
</div>
</div>

And the CSS is like this:

.whiteout {
    display: none;
    position: fixed;
    left: 0; top: 0; right: 0; bottom: 0;
    background-color: #fff; 
    background-color: rgba(255, 255, 255, 0.7);
}
.modal {
    position: fixed;
    left: 50%;
    top: 50%;
    z-index: 200;
    border: 12px solid #666;
    border: 12px solid rgba(0, 0, 0, 0.5);
    -moz-border-radius: 12px;
    border-radius: 12px;
}

I'm using jQuery to show the modal window when I click a link, with the "whiteout" background, and I want it to fade out when I click the background.

$('.share-link').click( function() {
    $('.whiteout').fadeIn();
    return false;
} );
$('.whiteout').click( function() { // click the background
    $(this).fadeOut();
} );
$('.modal-close').click( function() { // close button on the modal window
    $('.whiteout').fadeOut();
} );

However, it fades out whenever I click the modal window, as well as the background, because technically that is inside the "whiteout" element. Is it possible to stop that happening when I click inside the .modal element?

try this:

$('.whiteout').click( function(e) { // click the background
    if(e.target == this)
       $(this).fadeOut();
} );

The best thing might be to move the whiteout div to the end of the body, entirely outside the content area. With the right CSS, the whiteout element can live anywhere in the DOM but still achieve the right effect.

As an example, take a look at how jQuery UI's dialog works, it does almost exactly this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM