CSS/HTML Modal- Using the Escape key/Click outside to close

前端 未结 2 1403
名媛妹妹
名媛妹妹 2021-01-03 01:03

I have the following modal working,

http://jsfiddle.net/kumarmuthaliar/GG9Sa/1/

on my site. It\'s exactly what I want in terms of ease of use, and function.

2条回答
  •  悲哀的现实
    2021-01-03 01:17

    For this you will need a little javascript. Check the code with some comments.

    function modalClose() {
        if (location.hash == '#openModal') {
            location.hash = '';
        }
    }
    
    // Handle ESC key (key code 27)
    document.addEventListener('keyup', function(e) {
        if (e.keyCode == 27) {
            modalClose();
        }
    });
    
    var modal = document.querySelector('#openModal');
    
    // Handle click on the modal container
    modal.addEventListener('click', modalClose, false);
    
    // Prevent event bubbling if click occurred within modal content body
    modal.children[0].addEventListener('click', function(e) {
        e.stopPropagation();
    }, false);
    

    Demo: http://jsfiddle.net/GG9Sa/264/

    Note, that closing modal is technically possible with CSS/HTML only, however for handling Escape key press you will need Javascript.

提交回复
热议问题