1

Не понимаю, почему модальное окно исчезает и при клике на само окно, хотя я прописал, что оно будет исчезать только при клике на оверлей. Прописал окошку и z-index большой, не помогает.

$("button").click(function() {
  $(".main").addClass("show");
});
$(".main").click(function() {
  $(this).removeClass("show");
});
body {
  z-index: 1;
}

.main {
  opacity: 0;
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: #c2c2c2;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: -1;
  transition: .3s;
  .modal {
    width: 300px;
    height: 200px;
    background: #fff;
    z-index: 1000;
  }
}

button {
  z-index: 10;
}

.show {
  opacity: 1;
  z-index: 50;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <button>Нажми!</button>
  <div class="main">
    <div class="modal"></div>
  </div>
</body>
</html>

В вопросе само модальное окно уже не появляется, но в браузере его видно...

1 ответ 1

2

Событие click внутри .modal всплывает до .main.

$(".main").click(function(e) {
  if (e.target == this)
    $(this).removeClass("show");
});

или

$(".main").click(function(e) {
  if (!$(e.target).hasClass(".modal") && !$(e.target).parents(".modal").length)
    $(this).removeClass("show");
});

или

$(".modal").click(function(e) {
  e.stopPrpagation();
});

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

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