Tengo problemas para oscurecer el fondo cuando abro el modal. Encontré un montón de información sobre cómo hacer esto con bootstrap, pero estoy buscando una manera de hacerlo usando javascript. Actualmente tengo la apertura y el cierre modal cuando quiero, así que solo necesito implementar la función de fondo.
HTML
<body> <h1>Modal</h1> <button id="myBtn" data-toggle="modal fade" data-target="#myModal">Open Modal</button> <section class="modal hidden" id="myModal"> <span class="close">×</span> <h2>I am the modal</h2> <p>hello world</p> </section> </body>CSS
.modal { display: flex; justify-content: center; flex-direction: column; align-items: center; border: solid 2px black; border-radius: 10px; padding: 30px; margin: 20px 0; background-color: greenyellow; } .hidden{ display: none; }JS
var modal = document.getElementById("myModal"); var btn = document.getElementById("myBtn"); var span = document.getElementsByClassName("close")[0]; btn.onclick = function() { modal.style.display = "block"; } span.onclick = function() { modal.style.display = "none"; } window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } }Se agradecería cualquier ayuda o punto de partida sobre cómo implementar el telón de fondo.
Podría tener un div con la clase modalBackdrop para oscurecer el fondo. Puede hacer que ocupe toda la página y darle un color que tenga transparencia como rgba(0,0,0,0.2) . Puede reemplazar su HTML con lo siguiente para agregar un elemento div de fondo modal.
<body> <h1>Modal</h1> <button id="myBtn" data-toggle="modal fade" data-target="#myModal">Open Modal</button> <div class="modalBackdrop hidden"></div> <section class="modal hidden" id="myModal"> <span class="close">×</span> <h2>I am the modal</h2> <p>hello world</p> </section> </body>Y agregue los siguientes estilos a su CSS para el fondo modal
.modalBackdrop{ position:fixed; top:0; left:0; width:100vw; height:100vh; background-color:rgba(0,0,0,0.2); }Finalmente, reemplace su JS con lo siguiente para mostrar y ocultar el fondo cuando sea necesario
var modal = document.getElementById("myModal"); var btn = document.getElementById("myBtn"); var modalBackdrop = document.getElementsByClassName("modalBackdrop")[0]; var span = document.getElementsByClassName("close")[0]; btn.onclick = function() { modal.style.display = "block"; modalBackdrop.style.display = "block"; } span.onclick = function() { modal.style.display = "none"; modalBackdrop.style.display = "none"; } window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; modalBackdrop.style.display = "none"; } }Además, hacer que la transparencia sea más baja en el CSS hará que el fondo sea más oscuro al mostrar el modal.