【发布时间】:2022-01-08 04:48:58
【问题描述】:
我有一个响应式图片库,您可以在其中单击图片,它会以模式弹出,显示图片的完整视图。
然而,目前,关闭模式的唯一方法是使用右上角的“X”按钮
我想要的是能够通过单击图像上的任意位置来关闭模式。即在图像周围的黑色背景上
我附上了一个小提琴作为我的图片库当前的示例
任何帮助将不胜感激,谢谢!
https://jsfiddle.net/eoansv83/2/
HTML:
<div class="responsive">
<div class="gImg">
<img src="test.jpg">
<div class="desc">example 1</div>
</div>
</div>
<div class="responsive">
<div class="gImg">
<img src="test.jpg">
<div class="desc">example 2</div>
</div>
</div>
JavaScript:
// Get the modal
var modal = document.getElementById('myModal');
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// Get all images and insert the clicked image inside the modal
// Get the content of the image description and insert it inside the modal image caption
var images = document.getElementsByTagName('img');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
var i;
for (i = 0; i < images.length; i++) {
images[i].onclick = function() {
modal.style.display = "block";
modalImg.src = this.src;
modalImg.alt = this.alt;
captionText.innerHTML = this.nextElementSibling.innerHTML;
}
}
【问题讨论】:
标签: javascript html image modal-dialog