How to make modal close on click outside

后端 未结 7 718
误落风尘
误落风尘 2020-12-19 02:05

I have used this JavaScript below:

7条回答
  •  误落风尘
    2020-12-19 02:52

    Adding to this for future readers.

    Another way to dismiss the modal when clicking outside involved taking advantage of the bubbling nature of the javascript events.

    In a typical modal HTML structure

    
      
    -- Site content here

    clicking on .modal will cause the click event to propagate like this .modal -> #modal-root -> body while clicking outside the modal will only go through #modal-root -> body.

    Since we can stop the propagation of click events completely, and if that does not interfere with any other code, we only need to listen for click events in both .modal and #modal-root. A "modal-root" click will dismiss the modal, and a "modal" click will stop propagating the click event so never reaches the "modal-root".

    For extra clarity, here's the code working in codepen.io: https://codepen.io/nbalaguer/pen/PVbEjm

提交回复
热议问题