gpt4 book ai didi

javascript - 具有不同模态的图片

转载 作者:行者123 更新时间:2023-11-28 05:56:17 24 4
gpt4 key购买 nike

我对 JavaScript 很陌生,渴望了解更多信息。我尝试用模态做一些事情,但遇到了一个我似乎无法解决的困难。我想要四张彼此相邻的图片,当我单击它时,它会显示一个模式。因此,图 A 显示模态 A,图 B 显示模态 B,依此类推。我现在似乎只能让第一张图片正常工作,其他图片甚至没有显示模态。有人可以帮我解决这个问题吗?预先感谢您

   <div class = "StyleTextBox">
<h1>Present</h1>
<img id="myImg" src="C:/Users/s155310/Pictures/showcase pictures/guitar1.jpg" alt="guitar" width="200" height="auto">
<img id="myImg" src="C:/Users/s155310/Pictures/showcase pictures/1.jpg" alt="thing" width="200" height="auto">

//The Modal
<div id="myModal" class="modal">
<span class="close">×</span>
<img class="modal-content" id="img01">
<div id="caption"> </div>
<p> Some text </p>
</div>

<script>
// Get the modal
var modal = document.getElementById('myModal');

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

最佳答案

拥有多个具有相同 ID 的元素是无效的 HTML。您应该更改图像元素以改为使用类。在 JavaScript 中,您可以通过 document.getElementsByClassName('classNameHere') 访问这些类并通过循环迭代它们以设置 onclick 属性。例如:

<div class = "StyleTextBox">
<h1>Present</h1>
<img class="myImg" src="C:/Users/s155310/Pictures/showcase pictures/guitar1.jpg" alt="guitar" width="200" height="auto">
<img class="myImg" src="C:/Users/s155310/Pictures/showcase pictures/1.jpg" alt="thing" width="200" height="auto">

//The Modal
<div id="myModal" class="modal">
<span class="close">×</span>
<img class="modal-content" id="img01">
<div id="caption"> </div>
<p> Some text </p>
</div>

<script>
// Get the modal
var modal = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var images = document.getElementsByClassName('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
function openModel(){
modal.style.display = "block";
modalImg.src = this.src;
modalImg.alt = this.alt;
captionText.innerHTML = this.alt;
}
for(var img = 0; img < images.length; img++) {
images[img].onclick = openModel;
}

// 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";
}
</script>

关于javascript - 具有不同模态的图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37645284/

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