gpt4 book ai didi

javascript - 模态图像在类方面存在问题

转载 作者:行者123 更新时间:2023-12-01 00:49:24 25 4
gpt4 key购买 nike

我得到了这个模态脚本来在我的网站上显示更大的图像。效果很好,但只能处理 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 而不是类时,它运行良好 - 但我无法添加更多图像 - 这就是我需要使用类的原因。有人有什么想法吗?我将不胜感激

最佳答案

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

所以你必须循环遍历这个数组来添加事件,或者将这些图像放入容器中并使用event-delegation,这是一种更有效的方法。因为它只绑定(bind)事件一次。有关事件委托(delegate)的更多信息:https://javascript.info/event-delegation `

这是使用事件委托(delegate)的代码。

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>

关于javascript - 模态图像在类方面存在问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57109598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com