Несколько модальных можно закрыть только 1 - PullRequest
0 голосов
/ 21 марта 2020

Мне удалось создать несколько модальностей на моем веб-сайте, однако я могу закрыть только последний из трех, даже если у них есть 3 отдельные функции с 3 различными классами.

Как мне сделать так, чтобы каждый модал я открыл соответствующей кнопкой и закрыл, когда вы щелкаете из модального окна.

HTML

<div class="container flex bg-black-opacity mt-40 rounded pt-10 pb-12 mb-10 mx-auto items-center">
        <div class="container ml-5 cursor-pointer" id='1btn'>
            <img src="assets/img/merch-1.png" alt="" style='height: 400px;' class='shadow-pink'>
            <p class='uppercase mt-4 text-white'>Vice Versa 2020 Heather Grey Sweatshirt</p>
            <p class="text-white mt-4 ml-1 text-2xl">£15.00</p>

        </div>
        <div id="1mdl" class="modal1">

            <!-- Modal content -->
            <div class="modal-content">
              <p>Some text in the Modal..</p>
            </div>
        </div>
        <div class="container ml-5 cursor-pointer" id='2btn'>
            <img src="assets/img/merch-2.png" alt="" style='height: 400px;' class='shadow-pink'>
            <p class='uppercase mt-4 text-white'>Vice Versa 2020 Heather Grey Sweatshirt</p>
            <p class="text-white mt-4 ml-1 text-2xl">£15.00</p>

        </div>
        <div id="2mdl" class="modal2">

            <!-- Modal content -->
            <div class="modal-content">
              <p>Some text in the Modal..</p>
            </div>
        </div>
        <div class="container ml-5 cursor-pointer" id='3btn'>
            <img src="assets/img/merch-3.png" alt="" style='height: 400px;' class='shadow-pink'>
            <p class='uppercase mt-4 text-white'>Vice Versa 2020 Heather Grey Sweatshirt</p>
            <p class="text-white mt-4 ml-1 text-2xl">£15.00</p>

        </div>
        <div id="3mdl" class="modal3">

            <!-- Modal content -->
            <div class="modal-content">
              <p>Some text in the Modal..</p>
            </div>
        </div>

    </div>

CSS

 .modal1 {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
.modal2 {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
.modal3 {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
  background-color: #fefefe;
  margin: 15% auto; /* 15% from the top and centered */
  padding: 20px;
  border: 1px solid #888;
  width: 80%; /* Could be more or less, depending on screen size */
}

JavaScript

var modal1 = document.getElementById("1mdl");
var modal2 = document.getElementById("2mdl");
var modal3 = document.getElementById("3mdl");

var btn1 = document.getElementById("1btn");
var btn2 = document.getElementById("2btn");
var btn3 = document.getElementById("3btn");

btn1.onclick = function() {
  modal1.style.display = "block";
}
btn2.onclick = function() {
  modal2.style.display = "block";
}
btn3.onclick = function() {
  modal3.style.display = "block";
}
window.onclick = function(event) {
  if (event.target == modal1) {
    modal1.style.display = "none";
  }
} 
window.onclick = function(event) {
  if (event.target == modal2) {
    modal2.style.display = "none";
  }
} 
window.onclick = function(event) {
  if (event.target == modal3) {
    modal3.style.display = "none";
  }
} 

Ответы [ 3 ]

3 голосов
/ 21 марта 2020

Переназначение события click переопределяет предыдущую функцию обратного вызова с привязкой

, просто используйте это (сохраняйте его упрощенным, как в исходном вопросе)

 window.onclick = function(event) {
    if (event.target == modal1) {
        modal1.style.display = "none";
    } else if (event.target == modal2) {
        modal2.style.display = "none";
    } else
    if (event.target == modal3) {
        modal3.style.display = "none";
    }
}
1 голос
/ 21 марта 2020

Вы перезаписываете window.onlick снова и снова путем переназначения it.

Добавьте строки ниже

window.onclick = function(event) {
  if (
   event.target.id == modal1.id ||
   event.target.id == modal2.id ||
   event.target.id == modal3.id
  ) {
    document.getElementById(event.target.id).style.display = "none";
  }
}

Удалить ниже строк

window.onclick = function(event) {
  if (event.target == modal1) {
    modal1.style.display = "none";
  }
} 
window.onclick = function(event) {
  if (event.target == modal2) {
    modal2.style.display = "none";
  }
} 
window.onclick = function(event) {
  if (event.target == modal3) {
    modal3.style.display = "none";
  }
} 

Скользящая ссылка

0 голосов
/ 21 марта 2020

Вам не нужно использовать window.onlick 3 раза. Просто используйте общий класс для всех модальных, таких как "модальные", и измените также css. Используйте window.oncick, чтобы проверить, имеет ли цель класс «модальный», если он равен true, и не отображать его.

window.onclick = function(event) {
  if(event.target.classList.contains("modal")){
    event.target.style.display="none"; 
  }  
} 

Подробности в Codepen

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...