纯 JavaScript 模态图像的问题



我对模式弹出图像有问题。我有一个图像列表,并尝试使用此代码(进行了一些更改(: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal_img 但它仅适用于第一条消息。如何使其适用于库中的所有消息?

<div>
<div class="portfolio-overlay">
<img src="img/portfolio/Transeco-small.jpg">
<div class="portfolio-image-overlay image-overlay-content">
<div class="portfolio-icons">
<i class="icon-zoom-in open-big"><img src="img/portfolio/Transeco-big.jpg" class="img-closed"></i>                          
<a href="http://www.google.com" target="_blank"><i class="icon-link"></i></a>
</div>
</div>
</div>
</div>
<div>
<div class="portfolio-overlay">
<img src="img/portfolio/Transeco-small.jpg">
<div class="portfolio-image-overlay image-overlay-content">
<div class="portfolio-icons">
<i class="icon-zoom-in open-big"><img src="img/portfolio/Transeco-big.jpg" class="img-closed"></i>                          
<a href="http://www.google.com" target="_blank"><i class="icon-link"></i></a>
</div>
</div>
</div>
</div>
<div>
<div class="portfolio-overlay">
<img src="img/portfolio/Transeco-small.jpg">
<div class="portfolio-image-overlay image-overlay-content">
<div class="portfolio-icons">
<i class="icon-zoom-in open-big"><img src="img/portfolio/Transeco-big.jpg" class="img-closed"></i>                          
<a href="http://www.google.com" target="_blank"><i class="icon-link"></i></a>
</div>
</div>
</div>
</div>
<!-- The Modal -->
<div class="modal myModal">
<span class="close">&times;</span>
<img class="modal-content img01">
</div>

// Get the modal
var modal = document.querySelector(".myModal");
// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.querySelector('.open-big');
var modalImg = document.querySelector(".img01");
var probaa = document.querySelector('.open-big img');
img.onclick = function(){
modal.style.display = "block";
modalImg.src = probaa.src;
}
// 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";
}

控制台中没有错误,但它仅适用于冷杉映像...

var img = document.querySelector('.open-big');

document.querySelector只选择单个元素,在本例中为具有类的第一个元素open-big

为了选择所有元素,您必须使用document.querySelectorAll

然后,您可以遍历该集,并为每个事件侦听器添加事件侦听器:

var imgs = document.querySelectorAll('.open-big');
for (i = 0; i < imgs.length; ++i) {
imgs[i].onclick = function(){
modal.style.display = "block";
modalImg.src = probaa.src;
}
}

但是,您不能在节点集合上使用普通数组方法。 因此,imgs.forEach将不起作用。不过,有一个复杂的解决方法:

[].forEach.call(imgs, function(img) {
// do whatever
});

此链接中有更多关于 css 技巧的信息。

相关内容

  • 没有找到相关文章