У меня есть веб-страница с изображением. Когда я нажимаю на изображение, оно открывается модально. Когда я нажимаю кнопку закрытия, модальное окно закрывается. Однако когда я нажимаю за пределами модального окна, модальное окно не закрывается. Я добавил прослушиватель событий для обнаружения кликов, но не работает. Я пробовал аналогичные вопросы по stackoverflow, например добавление наложения поверх модуля, но все равно не работает. Я потерялся. Буду признателен за новые идеи.
document.addEventListener("DOMContentLoaded", function() {
var overlay = document.getElementById("overlay");
var modal = document.getElementById("imageModal");
var modalImg = document.getElementById("modalImage");
var captionText = document.getElementById("caption");
var closeButton = document.getElementsByClassName("close")[0];
// Open modal when image is clicked
document.querySelectorAll(".modal-trigger").forEach(function(img) {
img.onclick = function() {
overlay.style.display = "block";
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
});
// Close modal when close button is clicked
closeButton.onclick = function() {
overlay.style.display = "none";
modal.style.display = "none";
};
// Close modal when clicking outside of modal content
window.onclick = function(e) {
// Close if clicking directly on the overlay
if (e.target == overlay) {
overlay.style.display = "none";
modal.style.display = "none";
}
};
// Prevent clicks inside the modal from closing it
modal.onclick = function(event) {
event.stopPropagation(); // Prevent clicks inside the modal from closing it
};
});/* The Modal (background) */
.overlay {
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 */
background-color: rgba(0, 0, 0, 0.6); /* Semi-transparent background */
}
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 20px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgba(0, 0, 0, 0.6);
}
/* Modal Content (image) */
.modal-content {
margin: auto;
display: block;
width: 60%;
}
/* Caption of Modal Image (Image Text) - Add some padding */
#caption {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
text-align: center;
color: #ccc;
padding: 10px 0;
}
/* Add Animation - Zoom in the Modal */
.modal-content, #caption {
animation-name: zoom;
animation-duration: 0.6s;
}
@keyframes zoom {
from {transform: scale(0)}
to {transform: scale(1)}
}
/* The Close Button */
.close {
position: absolute;
top: 15px;
right: 35px;
color: #f1f1f1;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
}
.close:hover,
.close:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}
.timeline-item img {
display: block;
transition: opacity 0.3s ease, transform 0.3s ease;
cursor: pointer; /* Show a pointer cursor on hover */
}
.timeline-item img:hover {
opacity: 0.7;
transform: scale(1.05); /* Slightly enlarge the image on hover */
}<div class = "timeline-item" style = " left: 120px;">ABCDdgfgfhggfhg<img alt = "" class = "modal-trigger" src = "https://compote.slate.com/images/22ce4663-4205-4345-8489-bc914da1f272.jpeg?crop=1560%2C1040%2Cx0%2Cy0&width=1280" style = " position: relative; top: 70px; width: 215px; left: -30px;" />
</div>
<div id = "overlay" class = "overlay">
<div id = "imageModal" class = "modal">
<span class = "close">×</span>
<img class = "modal-content" id = "modalImage" />
<div id = "caption"></div>
</div>
</div>


![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


В вашем CSS указано (показаны только соответствующие части):
.modal {
/* ... elided ... */
position: fixed;
width: 100%;
height: 100%;
/* ... elided ... */
}
поэтому он охватывает всю область просмотра. Поэтому ваш window.onclick никогда не будет выполнен, потому что click захватывается элементом .modal.
Ниже приведена версия, которая работает. Я удалил прослушиватель window.onclick, поскольку он все равно никогда не выполняется, и переместил оператор if внутрь обработчика modal.onclick. Обратите внимание, что я дополнительно изменил условие в операторе: любой щелчок за пределами области изображения приведет к закрытию модального окна. Это означает, что вы также можете удалить обработчик closeButton.onclick.
document.addEventListener("DOMContentLoaded", function() {
var overlay = document.getElementById("overlay");
var modal = document.getElementById("imageModal");
var modalImg = document.getElementById("modalImage");
var captionText = document.getElementById("caption");
var closeButton = document.getElementsByClassName("close")[0];
// Open modal when image is clicked
document.querySelectorAll(".modal-trigger").forEach(function(img) {
img.onclick = function() {
overlay.style.display = "block";
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
});
// Close modal when close button is clicked
/*closeButton.onclick = function() {
overlay.style.display = "none";
modal.style.display = "none";
};*/
modal.onclick = function(event) {
event.stopPropagation(); // Prevent clicks inside the modal from closing it
if (event.target !== modalImg) {
overlay.style.display = "none";
modal.style.display = "none";
}
};
});/* The Modal (background) */
.overlay {
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 */
background-color: rgba(0, 0, 0, 0.6); /* Semi-transparent background */
}
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 20px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgba(0, 0, 0, 0.6);
}
/* Modal Content (image) */
.modal-content {
margin: auto;
display: block;
width: 60%;
}
/* Caption of Modal Image (Image Text) - Add some padding */
#caption {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
text-align: center;
color: #ccc;
padding: 10px 0;
}
/* Add Animation - Zoom in the Modal */
.modal-content, #caption {
animation-name: zoom;
animation-duration: 0.6s;
}
@keyframes zoom {
from {transform: scale(0)}
to {transform: scale(1)}
}
/* The Close Button */
.close {
position: absolute;
top: 15px;
right: 35px;
color: #f1f1f1;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
}
.close:hover,
.close:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}
.timeline-item img {
display: block;
transition: opacity 0.3s ease, transform 0.3s ease;
cursor: pointer; /* Show a pointer cursor on hover */
}
.timeline-item img:hover {
opacity: 0.7;
transform: scale(1.05); /* Slightly enlarge the image on hover */
}<div class = "timeline-item" style = " left: 120px;">ABCDdgfgfhggfhg<img alt = "" class = "modal-trigger" src = "https://compote.slate.com/images/22ce4663-4205-4345-8489-bc914da1f272.jpeg?crop=1560%2C1040%2Cx0%2Cy0&width=1280" style = " position: relative; top: 70px; width: 215px; left: -30px;" />
</div>
<div id = "overlay" class = "overlay">
<div id = "imageModal" class = "modal">
<span class = "close">×</span>
<img class = "modal-content" id = "modalImage" />
<div id = "caption"></div>
</div>
</div>
В модальном окне есть
width: 100%; height: 100%;. Таким образом, он охватывает все окно, нет «вне модального окна».