我对模式弹出图像有疑问。我有一张图像列表,并尝试使用此代码(进行了一些更改):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">×</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";
}
控制台中没有错误,但仅适用于冷杉图像...
答案 0 :(得分:0)
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
});