0

Есть код на 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";
    }
}

var modal1 = document.getElementById('myModal1');
var btn1 = document.getElementById("myBtn1");
var span1 = document.getElementsByClassName("close1")[0];

btn1.onclick = function() {
    modal1.style.display = "block";
}

span1.onclick = function() {
    modal1.style.display = "none";
}

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

Проблема в последней части кода:

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

Если его оставлять, то первое модальное окно можно закрыть только при нажатии на крестик. Если убрать, то наоборот. 1 модальное окно закрывается при клике в любую область, а 2 окно только при нажатии на крестик.

Подскажите, пожалуйста, где ошибка? Нужно, что бы они работали одинаково. И 1 и 2 окна закрывались и по нажатию на крестик и по нажатию в любую другую область (кроме нажатия на само окно).

HTML 1 окна:

<button id="myBtn">Открыть окно</button>
  <div id="myModal" class="modal">
    <div class="modal-content">
      <div class="modal-header">
        <span class="close">&times;</span>
        <h2>Шапка модального окна</h2>
      </div>
      <div class="modal-body">
        <p>Какой-то текст в теле модального окна</p>
        <p>Ещё другой текст...</p>
      </div>
      <div class="modal-footer">
        <h3>Футер модального окна</h3>
      </div>
    </div>
  </div>

2 окно:

<button id="myBtn1">Открыть окно</button>
  <div id="myModal1" class="modal1">
    <div class="modal1-content">
      <div class="modal1-header">
        <span class="close1">&times;</span>
        <h2>модального окна</h2>
      </div>
      <div class="modal1-body">
        <p>Какой-то текст в теле модального окна</p>
        <p>Ещё другой текст...</p>
      </div>
      <div class="modal1-footer">
        <h3>Футер модального окна</h3>
      </div>
    </div>
  </div>

css:

body {font-family: Arial, Helvetica, sans-serif;}

#myBtn {
  background-color: #9C27B0;
  color: white;
  padding: 12px 16px;
  font-size: 18px;
  font-weight: bold;
  border: none;
  cursor: pointer;
  width: 180px;
}


.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    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 {
    position: relative;
    background-color: #E1BEE7;
    margin: auto;
    padding: 0;
    border: 5px solid #7B1FA2;
    width: 50%;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
    -webkit-animation-name: animatetop;
    -webkit-animation-duration: 0.4s;
    animation-name: animatetop;
    animation-duration: 0.4s
}


@-webkit-keyframes animatetop {
    from {top:-300px; opacity:0} 
    to {top:0; opacity:1}
}

@keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
}


.close {
    color: white;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}

.modal-header {
    padding: 2px 16px;
    background-color: #9C27B0;
    color: white;
}

.modal-body {padding: 2px 16px;}

.modal-footer {
    padding: 2px 16px;
    background-color: #9C27B0;
    color: white;
}

#myBtn1 {
  background-color: #9C27B0;
  color: white;
  padding: 12px 16px;
  font-size: 18px;
  font-weight: bold;
  border: none;
  cursor: pointer;
  width: 180px;
}


.modal1 {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    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 */
}


.modal1-content {
    position: relative;
    background-color: #E1BEE7;
    margin: auto;
    padding: 0;
    border: 5px solid #7B1FA2;
    width: 50%;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
    -webkit-animation-name: animatetop;
    -webkit-animation-duration: 0.4s;
    animation-name: animatetop;
    animation-duration: 0.4s
}


@-webkit-keyframes animatetop {
    from {top:-300px; opacity:0} 
    to {top:0; opacity:1}
}

@keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
}


.close1 {
    color: white;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close1:hover,
.close1:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}

.modal1-header {
    padding: 2px 16px;
    background-color: #9C27B0;
    color: white;
}

.modal1-body {padding: 2px 16px;}

.modal1-footer {
    padding: 2px 16px;
    background-color: #9C27B0;
    color: white;
}
4
  • ru.stackoverflow.com/q/981378/256824
    – user256824
    29 июл 2019 в 6:03
  • @РустамГимранов добавил код html
    – Grimm
    29 июл 2019 в 18:30
  • css-a не хватает, чтобы посмотреть.
    – Crus
    29 июл 2019 в 20:43
  • @Crus добавил стили
    – Grimm
    29 июл 2019 в 21:04

1 ответ 1

1

Вот так вот будет работать правильно. Пример на jsfiddle тут - https://jsfiddle.net/crus/bqfmdcrp/9/

Вы 2 раза подряд вызывали window.onclick, и выполнялся только один.

window.onclick = function(e) {
    if (e.target == modal) {
        modal.style.display = "none";
        console.log('done');
    } else if (e.target == modal1) {
        modal1.style.display = "none";
        console.log('done');
    }
}
1
  • Огромнейшее вам спасибо!
    – Grimm
    29 июл 2019 в 22:59

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.