模态图像存在类问题

时间:2019-07-19 09:33:32

标签: javascript html

我得到了这个模式脚本,以便在我的网站上显示更大的图像。效果很好,但只有1张图片。当我尝试添加更多图像时-脚本不起作用,什么也没发生。有人可以告诉我我在做什么错吗?
这是一些代码:

var modal = document.getElementById("myModal");

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementsByClassName("zdjecie");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function() {
  modal.style.display = "block";
  modalImg.src = this.src;
  captionText.innerHTML = this.alt;
}

// 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";
}
<img class="zdjecie" style="max-height: 16rem;max-width: 16rem;" src="example.jpg">

当我使用ID代替类时,它工作得很好-但我无法添加更多图像-这就是为什么我需要使用类。有人有什么想法吗?我会很好

1 个答案:

答案 0 :(得分:2)

document.getElementsByClassName返回一个数组,其中包含所有具有zdjecie类的dom。

因此,您必须遍历此数组以添加事件,或将这些图像放入容器中并使用event-delegation,这是一种更有效的方法。因为它只绑定一次事件。有关event-delegation的更多信息:https://javascript.info/event-delegation`

这是使用event-delegation的代码。

var handleImageClick =  function(evt){
  if(evt.target.className.indexOf('zdjecie') === -1) return;
  modal.style.display = "block";
  modalImg.src = evt.target.src;
  captionText.innerHTML = evt.target.alt;
 
}
// Get the image and insert it inside the modal - use its "alt" text as a caption
var modal = document.getElementById("myModal");
var imageContainer = document.getElementById("imageContainer");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
imageContainer.addEventListener('click', handleImageClick)

// 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";
}
.zdjecie{
  background-color: yellow;
  width: 100px;
  height: 100px;
  display: inline-block;
}
<div id="imageContainer">
    <img class="zdjecie" alt="1"  style="max-height: 16rem;max-width: 16rem;" src="example1.jpg" />
    <img class="zdjecie" alt="2"  style="max-height: 16rem;max-width: 16rem;" src="example2.jpg" />
    <img class="zdjecie" alt="3" style="max-height: 16rem;max-width: 16rem;" src="example3.jpg" />
    <img class="zdjecie"  alt="4" style="max-height: 16rem;max-width: 16rem;" src="example4.jpg" />
</div>
<div id="myModal">
  <span class="close">x</span>
  <img id="img01" style="max-height: 16rem;max-width: 16rem;" />
  <p id="caption"></p>
</div>