HTML5 CSS3 modal window, close when click outside

2019-09-01 21:16发布

问题:

I use the modal window as described by Keenan Payne, made with HTML5 & CSS3. I would like it to close when the user clicks on the darkened background, outside the modal window. Does anybody knows how to do this?

Modal window by Keenan Payne: http://www.webdesignerdepot.com/2012/10/creating-a-modal-window-with-html5-and-css3/

回答1:

You have to change the target on something different than #openModal. You can import jQuery, put this in <head> section:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

and add this code right before </body> tag:

<script type="text/javascript">
    $("#openModal").click( function() {
        if (!$("#openModal>div").is(":hover")) document.location.href='#';
    });
</script>

So when user clicks on the overlay the target will change on '#' and the modal will be closed.